Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/server/src/server/createMcpHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,7 @@ export function createMcpHandler(factory: McpServerFactory, options: CreateMcpHa
inflight.add(server);
server.onclose = () => {
inflight.delete(server);
server.onclose = previousOnClose;
previousOnClose?.();
};

Expand Down
21 changes: 21 additions & 0 deletions packages/server/test/server/createMcpHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,27 @@ describe('createMcpHandler — modern path', () => {
expect(onerror).toHaveBeenCalledWith(expect.objectContaining({ message: 'factory exploded' }));
});

it('restores a reused server onclose handler after each modern exchange', async () => {
const reused = new McpServer({ name: 'entry-test-server', version: '1.0.0' });
reused.registerTool('echo', { inputSchema: z.object({ text: z.string() }) }, async ({ text }) => ({
content: [{ type: 'text', text }]
}));

const originalOnClose = vi.fn();
reused.server.onclose = originalOnClose;

const handler = createMcpHandler(() => reused);

for (let i = 0; i < 3; i++) {
const response = await handler.fetch(postRequest(modernToolsCall('echo', { text: `hello-${i}` })));
expect(response.status).toBe(200);
await response.text();
expect(reused.server.onclose).toBe(originalOnClose);
}

expect(originalOnClose).toHaveBeenCalledTimes(3);
});

it('closes and releases the per-request instance when a modern exchange fails internally', async () => {
const { factory, state } = testFactory();
const onerror = vi.fn();
Expand Down
Loading