-
Notifications
You must be signed in to change notification settings - Fork 11
fix: reuse pooled MCP client connections in pi extension #52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
EdwardIrby
wants to merge
6
commits into
main
Choose a base branch
from
fix/pi-mcp-client-reuse
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8c6739a
fix: reuse pooled MCP client connections in pi extension
EdwardIrby 80a8c90
feat: add You web search skill
EdwardIrby 81bd502
revert: remove You web search skill
EdwardIrby de1bdf7
fix: format structured MCP tool results
EdwardIrby 01c5a9b
fix: defer closing active MCP clients
EdwardIrby d4bea40
fix: propagate MCP tool execution errors
EdwardIrby File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| import { describe, expect, test } from 'bun:test' | ||
| import type { ExtensionAPI } from '@earendil-works/pi-coding-agent' | ||
| import { createMcpHandler, fromJsonSchema, McpServer } from '@modelcontextprotocol/server' | ||
|
|
||
| type RegisteredTool = { | ||
| name: string | ||
| execute: (_toolCallId: string, params: unknown) => Promise<unknown> | ||
| } | ||
|
|
||
| type RegisteredEvent = { | ||
| eventName: string | ||
| handler: (...args: never[]) => unknown | ||
| } | ||
|
|
||
| const loadExtension = async () => (await import(`../main.ts?test=${Date.now()}-${Math.random()}`)).default | ||
|
|
||
| const createPiHarness = () => { | ||
| const events: RegisteredEvent[] = [] | ||
| const tools: RegisteredTool[] = [] | ||
|
|
||
| const pi = { | ||
| on: (eventName: string, handler: (...args: never[]) => unknown) => { | ||
| events.push({ eventName, handler }) | ||
| }, | ||
| registerTool: (tool: RegisteredTool) => { | ||
| tools.push(tool) | ||
| }, | ||
| } as unknown as ExtensionAPI | ||
|
|
||
| return { events, pi, tools } | ||
| } | ||
|
|
||
| /** Real in-process MCP server: the extension's transport fetch is wired straight to handler.fetch. */ | ||
| const createTestServer = () => { | ||
| let initializeCount = 0 | ||
| let failNextToolCall = false | ||
|
|
||
| const handler = createMcpHandler(() => { | ||
| const server = new McpServer({ name: 'fixture', version: '1.0.0' }) | ||
| server.registerTool( | ||
| 'echo', | ||
| { | ||
| description: 'Echo the query back', | ||
| inputSchema: fromJsonSchema<{ query: string }>({ | ||
| type: 'object', | ||
| properties: { query: { type: 'string' } }, | ||
| required: ['query'], | ||
| }), | ||
| }, | ||
| async ({ query }) => ({ content: [{ type: 'text' as const, text: `echo:${query}` }] }), | ||
| ) | ||
| return server | ||
| }) | ||
|
|
||
| const fetchHandler = async (url: string | URL, init?: RequestInit) => { | ||
| const request = new Request(String(url), init) | ||
| if (request.method === 'POST') { | ||
| const body = (await request.clone().json()) as { method?: string } | ||
| if (body.method === 'initialize') initializeCount += 1 | ||
| if (body.method === 'tools/call' && failNextToolCall) { | ||
| failNextToolCall = false | ||
| throw new TypeError('fetch failed') | ||
| } | ||
| } | ||
| return handler.fetch(request) | ||
| } | ||
|
|
||
| return { | ||
| close: () => handler.close(), | ||
| failNextToolCall: () => { | ||
| failNextToolCall = true | ||
| }, | ||
| initializeCount: () => initializeCount, | ||
| serverConfig: { | ||
| url: 'http://fixture.local/mcp', | ||
| authenticated: false, | ||
| fetch: fetchHandler, | ||
| promptGuidelines: ['fixture server'], | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| const findTool = (tools: RegisteredTool[], name: string) => { | ||
| const tool = tools.find((registeredTool) => registeredTool.name === name) | ||
| expect(tool).toBeDefined() | ||
| if (!tool) throw new Error(`${name} tool was not registered`) | ||
| return tool | ||
| } | ||
|
|
||
| describe('MCP connection lifecycle', () => { | ||
| test('reuses one MCP connection across tool executions', async () => { | ||
| const server = createTestServer() | ||
| try { | ||
| const extension = await loadExtension() | ||
| const { pi, tools } = createPiHarness() | ||
|
|
||
| await extension(pi, [server.serverConfig]) | ||
| // Tool discovery pays its own one-shot handshake; start counting from here. | ||
| const afterDiscovery = server.initializeCount() | ||
|
|
||
| const tool = findTool(tools, 'echo') | ||
| const first = (await tool.execute('call-1', { query: 'one' })) as { content: Array<{ text: string }> } | ||
| const second = (await tool.execute('call-2', { query: 'two' })) as { content: Array<{ text: string }> } | ||
|
|
||
| expect(first.content[0]?.text).toBe('echo:one') | ||
| expect(second.content[0]?.text).toBe('echo:two') | ||
| expect(server.initializeCount()).toBe(afterDiscovery + 1) | ||
| } finally { | ||
| await server.close() | ||
| } | ||
| }) | ||
|
|
||
| test('reconnects and retries once when the connection drops', async () => { | ||
| const server = createTestServer() | ||
| try { | ||
| const extension = await loadExtension() | ||
| const { pi, tools } = createPiHarness() | ||
|
|
||
| await extension(pi, [server.serverConfig]) | ||
| const afterDiscovery = server.initializeCount() | ||
|
|
||
| const tool = findTool(tools, 'echo') | ||
| await tool.execute('call-1', { query: 'one' }) | ||
| expect(server.initializeCount()).toBe(afterDiscovery + 1) | ||
|
|
||
| server.failNextToolCall() | ||
| const result = (await tool.execute('call-2', { query: 'two' })) as { content: Array<{ text: string }> } | ||
|
|
||
| expect(result.content[0]?.text).toBe('echo:two') | ||
| // The dropped pooled client was replaced: one new handshake, then success. | ||
| expect(server.initializeCount()).toBe(afterDiscovery + 2) | ||
| } finally { | ||
| await server.close() | ||
| } | ||
| }) | ||
|
|
||
| test('closes pooled clients on session_shutdown', async () => { | ||
| const server = createTestServer() | ||
| try { | ||
| const extension = await loadExtension() | ||
| const { events, pi, tools } = createPiHarness() | ||
|
|
||
| await extension(pi, [server.serverConfig]) | ||
| const afterDiscovery = server.initializeCount() | ||
|
|
||
| const tool = findTool(tools, 'echo') | ||
| await tool.execute('call-1', { query: 'one' }) | ||
| expect(server.initializeCount()).toBe(afterDiscovery + 1) | ||
|
|
||
| const shutdown = events.find((event) => event.eventName === 'session_shutdown') | ||
| expect(shutdown).toBeDefined() | ||
| if (!shutdown) throw new Error('session_shutdown handler was not registered') | ||
| await shutdown.handler() | ||
|
|
||
| await tool.execute('call-2', { query: 'two' }) | ||
| // Shutdown dropped the pooled client: the next execution reconnects. | ||
| expect(server.initializeCount()).toBe(afterDiscovery + 2) | ||
| } finally { | ||
| await server.close() | ||
| } | ||
| }) | ||
| }) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P1] resetMcpClient closes a shared pooled connection out from under concurrent in-flight callers
mcpClientsis module-level shared state, andgetMcpClientreturns the sameClientobject to every concurrent caller keyed by server. When twocallToolinvocations to the same server run concurrently and one throws,withPooledMcpClient's catch callsresetMcpClient, which callscloseMcpConnection(transport.terminateSession()+client.close()) on that shared connection while the other caller'scallToolis still in flight on it. That in-flight call then fails or hangs on a torn-down transport; that caller's own catch then callsresetMcpClientagain and can close the fresh connection the first retrier just cached, cascading failures. The same class of hazard exists incloseMcpClientsonsession_shutdown. There is no in-flight reference counting to prevent closing a connection that outstanding callers are using. Trigger: two concurrent tool calls to the same MCP URL where one fails. Fix: track in-flight callers per connection and defer close until the last caller drains, or have each caller snapshot its own connection and only close the old one once all outstanding callers have finished.