@dev-crowagent/pigeon-mcp 0.0.0-stage → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/CHANGELOG.md +143 -0
  2. package/README.md +256 -2
  3. package/THIRD_PARTY_NOTICES/modelcontextprotocol-typescript-sdk.txt +21 -0
  4. package/dist/auth-provider.d.ts +19 -0
  5. package/dist/auth-provider.d.ts.map +1 -0
  6. package/dist/auth-provider.js +2 -0
  7. package/dist/auth-provider.js.map +1 -0
  8. package/dist/client.d.ts +193 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +747 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/config-schema.d.ts +105 -0
  13. package/dist/config-schema.d.ts.map +1 -0
  14. package/dist/config-schema.js +101 -0
  15. package/dist/config-schema.js.map +1 -0
  16. package/dist/config.d.ts +57 -0
  17. package/dist/config.d.ts.map +1 -0
  18. package/dist/config.js +160 -0
  19. package/dist/config.js.map +1 -0
  20. package/dist/index.d.ts +16 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +14 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/input-schema.d.ts +7 -0
  25. package/dist/input-schema.d.ts.map +1 -0
  26. package/dist/input-schema.js +13 -0
  27. package/dist/input-schema.js.map +1 -0
  28. package/dist/model-content.d.ts +19 -0
  29. package/dist/model-content.d.ts.map +1 -0
  30. package/dist/model-content.js +67 -0
  31. package/dist/model-content.js.map +1 -0
  32. package/dist/naming.d.ts +23 -0
  33. package/dist/naming.d.ts.map +1 -0
  34. package/dist/naming.js +37 -0
  35. package/dist/naming.js.map +1 -0
  36. package/dist/oauth/auth-provider.d.ts +52 -0
  37. package/dist/oauth/auth-provider.d.ts.map +1 -0
  38. package/dist/oauth/auth-provider.js +97 -0
  39. package/dist/oauth/auth-provider.js.map +1 -0
  40. package/dist/oauth/callback.d.ts +48 -0
  41. package/dist/oauth/callback.d.ts.map +1 -0
  42. package/dist/oauth/callback.js +121 -0
  43. package/dist/oauth/callback.js.map +1 -0
  44. package/dist/oauth/client-settings.d.ts +107 -0
  45. package/dist/oauth/client-settings.d.ts.map +1 -0
  46. package/dist/oauth/client-settings.js +114 -0
  47. package/dist/oauth/client-settings.js.map +1 -0
  48. package/dist/oauth/discovery.d.ts +30 -0
  49. package/dist/oauth/discovery.d.ts.map +1 -0
  50. package/dist/oauth/discovery.js +156 -0
  51. package/dist/oauth/discovery.js.map +1 -0
  52. package/dist/oauth/errors.d.ts +32 -0
  53. package/dist/oauth/errors.d.ts.map +1 -0
  54. package/dist/oauth/errors.js +58 -0
  55. package/dist/oauth/errors.js.map +1 -0
  56. package/dist/oauth/flow.d.ts +112 -0
  57. package/dist/oauth/flow.d.ts.map +1 -0
  58. package/dist/oauth/flow.js +360 -0
  59. package/dist/oauth/flow.js.map +1 -0
  60. package/dist/oauth/index.d.ts +11 -0
  61. package/dist/oauth/index.d.ts.map +1 -0
  62. package/dist/oauth/index.js +9 -0
  63. package/dist/oauth/index.js.map +1 -0
  64. package/dist/oauth/loopback.d.ts +51 -0
  65. package/dist/oauth/loopback.d.ts.map +1 -0
  66. package/dist/oauth/loopback.js +98 -0
  67. package/dist/oauth/loopback.js.map +1 -0
  68. package/dist/oauth/provider.d.ts +62 -0
  69. package/dist/oauth/provider.d.ts.map +1 -0
  70. package/dist/oauth/provider.js +118 -0
  71. package/dist/oauth/provider.js.map +1 -0
  72. package/dist/oauth/sign-in.d.ts +73 -0
  73. package/dist/oauth/sign-in.d.ts.map +1 -0
  74. package/dist/oauth/sign-in.js +182 -0
  75. package/dist/oauth/sign-in.js.map +1 -0
  76. package/dist/oauth/types.d.ts +83 -0
  77. package/dist/oauth/types.d.ts.map +1 -0
  78. package/dist/oauth/types.js +113 -0
  79. package/dist/oauth/types.js.map +1 -0
  80. package/dist/output-limit.d.ts +24 -0
  81. package/dist/output-limit.d.ts.map +1 -0
  82. package/dist/output-limit.js +58 -0
  83. package/dist/output-limit.js.map +1 -0
  84. package/dist/protocol/content.d.ts +83 -0
  85. package/dist/protocol/content.d.ts.map +1 -0
  86. package/dist/protocol/content.js +41 -0
  87. package/dist/protocol/content.js.map +1 -0
  88. package/dist/protocol/http-headers.d.ts +31 -0
  89. package/dist/protocol/http-headers.d.ts.map +1 -0
  90. package/dist/protocol/http-headers.js +129 -0
  91. package/dist/protocol/http-headers.js.map +1 -0
  92. package/dist/protocol/jsonrpc.d.ts +64 -0
  93. package/dist/protocol/jsonrpc.d.ts.map +1 -0
  94. package/dist/protocol/jsonrpc.js +74 -0
  95. package/dist/protocol/jsonrpc.js.map +1 -0
  96. package/dist/protocol/stateless.d.ts +47 -0
  97. package/dist/protocol/stateless.d.ts.map +1 -0
  98. package/dist/protocol/stateless.js +102 -0
  99. package/dist/protocol/stateless.js.map +1 -0
  100. package/dist/protocol/types.d.ts +156 -0
  101. package/dist/protocol/types.d.ts.map +1 -0
  102. package/dist/protocol/types.js +12 -0
  103. package/dist/protocol/types.js.map +1 -0
  104. package/dist/result-schema.d.ts +10 -0
  105. package/dist/result-schema.d.ts.map +1 -0
  106. package/dist/result-schema.js +78 -0
  107. package/dist/result-schema.js.map +1 -0
  108. package/dist/testing/index.d.ts +2 -0
  109. package/dist/testing/index.d.ts.map +1 -0
  110. package/dist/testing/index.js +2 -0
  111. package/dist/testing/index.js.map +1 -0
  112. package/dist/transports/in-memory.d.ts +19 -0
  113. package/dist/transports/in-memory.d.ts.map +1 -0
  114. package/dist/transports/in-memory.js +50 -0
  115. package/dist/transports/in-memory.js.map +1 -0
  116. package/dist/transports/lines.d.ts +34 -0
  117. package/dist/transports/lines.d.ts.map +1 -0
  118. package/dist/transports/lines.js +85 -0
  119. package/dist/transports/lines.js.map +1 -0
  120. package/dist/transports/pipe.d.ts +49 -0
  121. package/dist/transports/pipe.d.ts.map +1 -0
  122. package/dist/transports/pipe.js +96 -0
  123. package/dist/transports/pipe.js.map +1 -0
  124. package/dist/transports/stdio.d.ts +29 -0
  125. package/dist/transports/stdio.d.ts.map +1 -0
  126. package/dist/transports/stdio.js +170 -0
  127. package/dist/transports/stdio.js.map +1 -0
  128. package/dist/transports/streamable-http.d.ts +113 -0
  129. package/dist/transports/streamable-http.d.ts.map +1 -0
  130. package/dist/transports/streamable-http.js +586 -0
  131. package/dist/transports/streamable-http.js.map +1 -0
  132. package/dist/transports/transport.d.ts +48 -0
  133. package/dist/transports/transport.d.ts.map +1 -0
  134. package/dist/transports/transport.js +38 -0
  135. package/dist/transports/transport.js.map +1 -0
  136. package/package.json +65 -5
package/CHANGELOG.md ADDED
@@ -0,0 +1,143 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ### Added
6
+
7
+ - Added MCP `2026-07-28`, the stateless protocol revision. `McpClient` still sends `initialize` first, so servers of earlier revisions see no change. It switches to `server/discover` and the stateless revision only for servers that reject `initialize`. `protocol: "2026-07-28"` speaks only that revision. Supports multi round-trip requests (answered with the client's request handlers, such as `roots/list`), the `Mcp-Method`, `Mcp-Name`, and `Mcp-Param-*` HTTP headers, and `logLevel` for servers' log messages. Based on [#12479](https://github.com/pooraddyy/pi/pull/12479) by [@dmmulroy](https://github.com/dmmulroy) ([#10416](https://github.com/pooraddyy/pi/issues/10416))
8
+ - Added `McpClient.listen(filter)` for `subscriptions/listen` streams of `2026-07-28` servers, `McpInitializeRejectedError` for connections whose `initialize` and `server/discover` both failed, `McpTransport.sendsHeaders` for transports whose messages are HTTP requests, and the `connectTimeoutMs` client option
9
+ - Added `protocol` to the shared `mcpServers` config fields (`"auto"` or `"2026-07-28"`)
10
+ - Added hooks for MCP extensions on the stateless revision: `extensions` in `ClientCapabilities` and `ServerCapabilities`, and the `onExtensionResult` request option, which answers results of extension result types (such as `upload_required` of the files extension) with the `requestState` to send the request again with ([#12600](https://github.com/pooraddyy/pi/issues/12600))
11
+ - Added the `./config-schema` export: the `mcpServers` shape as a JSON Schema, which the config types derive from and applications build their published config schemas on ([#12563](https://github.com/pooraddyy/pi/issues/12563))
12
+
13
+ ### Changed
14
+
15
+ - `McpStdioServerConfig`, `McpHttpServerConfig`, and `McpOAuthConfig` are now derived from the config schema; `McpHttpServerConfig.type` now includes `"streamable-http"`, which the validator always accepted ([#12563](https://github.com/pooraddyy/pi/issues/12563))
16
+
17
+ ## [1.7.0] - 2026-11-27
18
+
19
+ ## [1.6.1] - 2026-11-25
20
+
21
+ ### Added
22
+
23
+ - Added `createMcpResultSchema(outputSchema)`, moved from pi's coding agent: the output schema of an MCP tool for programs that call it, the whole `CallToolResult` with the tool's own output schema as `structuredContent` (its local `$ref`s rewritten to resolve there).
24
+ - Added `toMcpModelContent(server, result, options)`, moved from pi's coding agent: a result's model-facing content with embedded text blobs as text, binary resources saved through the caller's `McpOutputSaver` (left out without one), and resource links that name the caller's `readResourceTool`.
25
+
26
+ ### Fixed
27
+
28
+ - Fixed requests to servers that echo request IDs as strings (`"1"` for `1`) timing out instead of matching the response ([#12205](https://github.com/pooraddyy/pi/issues/12205))
29
+ - Fixed Streamable HTTP SSE events that arrive in many chunks taking time quadratic in their size, which blocked the event loop for seconds on multi-MiB tool results ([#12224](https://github.com/pooraddyy/pi/issues/12224))
30
+
31
+ ## [1.6.0] - 2026-11-20
32
+
33
+ ### Added
34
+
35
+ - Added `mcpServerSummary(description, instructions)`, a server's one-line summary for the system prompt as pi's coding agent shows it: the first line of the configured `description`, else of the server's `initialize` instructions.
36
+
37
+ ## [1.5.2] - 2026-11-10
38
+
39
+ ## [1.5.1] - 2026-11-09
40
+
41
+ ### Added
42
+
43
+ - Added `PipeTransport`, MCP's stdio transport over a program started by the caller through an `McpPipe` (`write`, `closeStdin`, `close`, `exited`), for example `@dev-crowagent/pi-env`'s `openProcess()` on another machine. `StdioTransport` and `PipeTransport` share the newline-delimited framing and the stderr tail.
44
+ - Added MCP OAuth sign-in in two halves (`@dev-crowagent/pi-mcp/oauth`), moved from pi's coding agent: `startMcpSignIn()` refreshes the stored tokens or returns the authorization URL, and `completeMcpSignIn()` exchanges the code later, possibly in another request with the same state store. The code comes from a loopback callback server (`listenForLoopbackSignIn()`, `waitForLoopbackSignIn()`), the application's own callback route, or a pasted redirect URL (`responseFromRedirectUrl()`). Client ID Metadata Documents (`clientMetadataDocuments`) and the client name are the caller's. Aborting a sign-in's `signal` also stops `startMcpSignIn()` while it waits for the refresh lock; a store's `withRefreshLock()` throws `McpRefreshLockBusyError` when another process holds the lock too long, which makes `startMcpSignIn()` skip the refresh, while any other lock failure fails the sign-in. Also added `createMcpAuthProvider()`, which refreshes tokens once across requests and, through `McpOAuthServerStore.withRefreshLock()`, across processes; its `redirectUrl` option names a redirect URI the application signs in with, so tokens from a Client ID Metadata Document that lists only an https callback route can be refreshed. Also added the `refreshOnly` option of `authorizeMcp()`, which refreshes without registering a client or replacing a pending authorization's `state` and PKCE verifier.
45
+ - Added helpers that let applications name and configure MCP tools like pi's coding agent, moved from it: `createMcpToolName()` (`mcp__<server>__<tool>`, sanitized, with a hash suffix for long or colliding names) and `mcpNamespace()`; `normalizeMcpInputSchema()`, which makes an input schema an object schema; `limitMcpContent()` and `MCP_OUTPUT_MAX_BYTES`, which cut model-facing text over 20KB in the middle and optionally save the full text through a caller's `McpOutputSaver`; and `validateMcpServerConfig()`, which validates one entry of the `mcpServers` configuration shape (stdio, Streamable HTTP, `oauth`, `enabled`, `description`, `timeout`), returns the entry tagged with its transport, and keeps the application's own fields for it to check afterwards. `isMcpServerOverride()` recognizes entries that only override a server defined elsewhere.
46
+
47
+ ### Fixed
48
+
49
+ - The third-party licenses are in `THIRD_PARTY_NOTICES/`, renamed from `LICENSES/`, which Vite's license notices read as the package's license file, failing browser builds that bundle the package.
50
+ - Fixed Streamable HTTP `application/json` responses bypassing `maxMessageBytes`; oversized JSON responses are now cancelled and rejected like oversized SSE events ([#11335](https://github.com/pooraddyy/pi/issues/11335))
51
+ - Fixed Streamable HTTP errors reading the whole HTTP error body; only the first 8 KiB kept in the error is read, and the rest is cancelled
52
+ - Fixed `OAuthCallbackServer.close()` waiting for minutes when the browser kept an unused connection open to the callback port, for example a preconnect. It now closes the remaining connections ([#11311](https://github.com/pooraddyy/pi/issues/11311))
53
+ - Fixed large MCP stdio messages being repeatedly copied and scanned as chunks arrived, causing slow tool responses ([#11761](https://github.com/pooraddyy/pi/issues/11761))
54
+ - Fixed MCP Streamable HTTP SSE replies with CR-only line endings failing with "stream ended without a response" ([#11764](https://github.com/pooraddyy/pi/issues/11764))
55
+ - Fixed oversized MCP SSE responses keeping their HTTP connections open after the message-size limit rejected them ([#11729](https://github.com/pooraddyy/pi/issues/11729))
56
+ - Fixed MCP stdio server subprocesses surviving disconnect or pi exit on POSIX when the server's main process had already exited ([#11721](https://github.com/pooraddyy/pi/issues/11721))
57
+
58
+ ## [1.5.0] - 2026-11-02
59
+
60
+ ### Changed
61
+
62
+ - README: the `AgentTool` wrapping example passes the MCP input schema as plain JSON Schema instead of through TypeBox's `Type.Unsafe`.
63
+
64
+ ### Fixed
65
+
66
+ - OAuth metadata parsing and `startAuthorization()` now accept only `http:` and `https:` URLs. Before, a server could supply a `file:` or custom protocol authorization endpoint (for example `search-ms:`), which the platform URL handler would launch on sign-in.
67
+ - Fixed the excerpt of an HTTP error body in Streamable HTTP errors keeping the whole response body alive ([#9265](https://github.com/pooraddyy/pi/issues/9265))
68
+
69
+ ## [1.4.0] - 2026-10-21
70
+
71
+ ## [1.3.0] - 2026-10-15
72
+
73
+ ## [1.2.0] - 2026-10-12
74
+
75
+ ### Breaking Changes
76
+
77
+ - Changed `CallToolResult.structuredContent` from `Record<string, unknown>` to `unknown`: `callTool()` now accepts any JSON value as structured content, including arrays and `null`, as MCP 2026-07-28 allows, instead of failing with "Invalid MCP tools/call structured content" ([#10416](https://github.com/pooraddyy/pi/issues/10416))
78
+
79
+ ### Fixed
80
+
81
+ - Fixed `authorizeMcp()` exchanging an authorization code whose `iss` parameter could not be checked because no authorization server metadata was discovered. It now throws `OAuthIssuerMismatchError`, whose `expected` is `undefined` in that case (RFC 9207). Reported by [@AizenvoltPrime](https://github.com/AizenvoltPrime)
82
+ - Fixed `StreamableHttpTransport` retrying a request after an authorization refresh even though the caller had already cancelled it or it had timed out, so the server still executed it. `McpTransport.send()` now takes an optional `signal`, which `McpClient` aborts once a request settles ([#10598](https://github.com/pooraddyy/pi/issues/10598))
83
+
84
+ ## [1.1.0] - 2026-10-07
85
+
86
+ ### Added
87
+
88
+ - Added a `signal` option to `authorizeMcp()`, `registerClient()`, the token request functions, and the discovery functions, which aborts their requests. An aborted refresh no longer falls back to a new authorization ([#10565](https://github.com/pooraddyy/pi/issues/10565))
89
+
90
+ ### Fixed
91
+
92
+ - Fixed `StreamableHttpTransport.close()` calling `AuthProvider.token()`, which could refresh tokens over the network before the session DELETE and delay closing; the DELETE now reuses the token of the last request ([#10565](https://github.com/pooraddyy/pi/issues/10565))
93
+
94
+ ## [1.0.4] - 2026-10-05
95
+
96
+ ### Fixed
97
+
98
+ - Fixed dynamic client registration failing on OpenID Connect authorization servers with `invalid_redirect_uri` for loopback redirect URIs. `registerClient()` now sends `application_type` (MCP SEP-837), derived from `redirect_uris` when `OAuthClientMetadata.application_type` is not set: `native` for loopback hosts and custom schemes, otherwise `web` ([#10493](https://github.com/pooraddyy/pi/issues/10493))
99
+
100
+ ## [1.0.3] - 2026-10-05
101
+
102
+ ## [1.0.2] - 2026-10-04
103
+
104
+ ## [1.0.1] - 2026-10-03
105
+
106
+ ### Breaking Changes
107
+
108
+ - `OAuthClientProvider.clientMetadataUrl` is replaced by `clientMetadataDocument(metadata)`, which returns the document URL and its redirect URI per authorization server, or `undefined` to register dynamically. It is called whenever no client information is stored, also when the server does not advertise support, and the document is no longer stored as client information ([#10302](https://github.com/pooraddyy/pi/issues/10302))
109
+
110
+ ### Added
111
+
112
+ - `McpOAuthProviderOptions.clientMetadataDocument`, `OAuthCallbackServerOptions.extraPaths`, and a `path` argument for `OAuthCallbackServer.waitForCallback` that rejects responses on other paths ([#10302](https://github.com/pooraddyy/pi/issues/10302))
113
+
114
+ ## [1.0.0] - 2026-10-01
115
+
116
+ ### Added
117
+
118
+ - Added an `authorizationServerMetadataUrl` option to `authorizeMcp()` to use a configured authorization server metadata document instead of discovery ([#10172](https://github.com/pooraddyy/pi/issues/10172)).
119
+ - Added an `iss` option to `authorizeMcp()`. The authorization code is only exchanged when `iss` names the flow's authorization server, or is absent and the server's metadata does not set `authorization_response_iss_parameter_supported` (RFC 9207).
120
+ - Added `stepUpScope()`, which combines the scopes of an `insufficient_scope` challenge with the scopes granted so far.
121
+
122
+ ### Fixed
123
+
124
+ - Fixed OAuth token and client registration responses with an empty or `null` optional field (such as `"scope": ""`) failing with `Invalid scope` and similar errors; such fields are now treated as absent ([#10266](https://github.com/pooraddyy/pi/issues/10266)).
125
+ - Fixed `expires_in: null` in a token response marking the access token as already expired.
126
+ - Fixed invalid URLs in protected resource metadata aborting OAuth discovery instead of falling back to the MCP server's origin.
127
+ - Fixed an empty requested scope, from `scope=""` in a `WWW-Authenticate` challenge or an empty `scopes_supported`, overriding the next scope source.
128
+ - Fixed list pagination failing with a duplicate cursor error when a server ends pagination with `nextCursor: ""` or `null`.
129
+ - Fixed step-up authorization in `adaptOAuthProvider()` requesting only the scopes of the `insufficient_scope` challenge. The new token lost the scopes granted before, so other requests failed with `insufficient_scope` again. Tokens now record their granted scope, which is the requested scope when the token response omits `scope`.
130
+
131
+ ## [0.99.2] - 2026-09-30
132
+
133
+ ### Fixed
134
+
135
+ - Fixed `StreamableHttpTransport` failing every request on Cloudflare Workers with `Illegal invocation` by calling `fetch`, including `UnauthorizedContext.fetch`, without a receiver ([#10188](https://github.com/pooraddyy/pi/issues/10188))
136
+
137
+ ## [0.99.1] - 2026-09-29
138
+
139
+ ## [0.99.0] - 2026-09-29
140
+
141
+ ### Added
142
+
143
+ - Added a standalone MCP client with JSON-RPC lifecycle, tool discovery and calls, cancellation, progress, roots, stdio and Streamable HTTP transports, and an in-memory testing transport.
package/README.md CHANGED
@@ -1,3 +1,257 @@
1
- # Temporary Holding Version
1
+ # @dev-crowagent/pigeon-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small, standalone Model Context Protocol client. It does not depend on the official MCP SDK or other pigeon packages.
4
+
5
+ The package provides a transport-neutral client core, stdio and Streamable HTTP transports, a stdio transport over a pipe to a program started elsewhere, and an in-memory testing transport.
6
+
7
+ ## Usage
8
+
9
+ ```typescript
10
+ import { McpClient, StdioTransport } from "@dev-crowagent/pigeon-mcp";
11
+
12
+ const transport = new StdioTransport({
13
+ command: "npx",
14
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"],
15
+ });
16
+ const client = new McpClient({
17
+ name: "my-client",
18
+ version: "1.0.0",
19
+ roots: [{ uri: "file:///workspace", name: "workspace" }],
20
+ });
21
+
22
+ await client.connect(transport);
23
+ const tools = await client.listTools();
24
+ const result = await client.callTool("search", { query: "MCP" });
25
+ await client.close();
26
+ ```
27
+
28
+ For a remote server, use `new StreamableHttpTransport({ url, headers })`. Fetch can be injected for proxying or custom networking.
29
+
30
+ An MCP transport owns framing and I/O. It delivers individual JSON-RPC messages to `McpClient`; the client owns request correlation, initialization, timeouts, cancellation, server requests, and protocol-level helpers.
31
+
32
+ ### Protocol versions
33
+
34
+ MCP `2026-07-28` is a stateless revision: there is no `initialize` handshake and no session, and every request carries the protocol version and the client's info and capabilities in `_meta`. Earlier revisions start with `initialize`.
35
+
36
+ `McpClient` sends `initialize` first, so servers of every earlier revision see what they always saw. Servers that speak both revisions answer it and stay on the earlier one. Only when a server rejects `initialize` (with a JSON-RPC error, or over HTTP with status 400) does the client send `server/discover` and, when the server lists `2026-07-28`, speak that. When `server/discover` fails as well, `connect()` fails with an `McpInitializeRejectedError` (`rejection`, `discoverError`). Some stdio servers that only speak `2026-07-28` exit after rejecting `initialize`, or refuse `server/discover` on that process; a new process connected with `protocol: "2026-07-28"` works with them, as pigeon's coding agent does. `protocol: "2026-07-28"` skips `initialize` and speaks only the stateless revision, also to servers that speak both.
37
+
38
+ On the stateless revision, the client:
39
+
40
+ - answers results that ask for input (`resultType: "input_required"`) with the handler of the input request's method (`roots/list` from `roots`, or one registered with `setRequestHandler`), and sends the request again with the answers. Input it has no handler for fails the request.
41
+ - over HTTP (transports with `sendsHeaders`), sends `Mcp-Method`, `Mcp-Name`, and the `Mcp-Param-*` headers that tools' `x-mcp-header` annotations ask for, leaves out tools whose annotations are invalid (reported through `onError`), and lists the tools again once when the server reports mismatching headers.
42
+ - asks for log messages at `logLevel` with every request, when that option is set.
43
+ - pings with `server/discover`, as the revision has no `ping`.
44
+
45
+ #### Extensions
46
+
47
+ MCP extensions (such as `io.modelcontextprotocol/files` for file uploads) are declared in `capabilities.extensions`, which goes with every request; `serverCapabilities.extensions` holds what the server supports. Results of the extensions' own result types fail the request unless the request names `onExtensionResult`. Its handler receives the whole result, does what the extension asks for, and returns the `requestState` to continue with; the client sends the same request again (same params and headers, new id) with that `requestState`. If the handler throws, or a later attempt fails, nothing is sent again.
48
+
49
+ ```typescript
50
+ const client = new McpClient({
51
+ name: "my-app",
52
+ version: "1.0.0",
53
+ capabilities: { extensions: { "io.modelcontextprotocol/files": { upload: {} } } },
54
+ });
55
+ await client.connect(transport);
56
+ const result = await client.callTool("save_to_folder", args, {
57
+ onExtensionResult: async ({ resultType, uploads, requestState }, { signal }) => {
58
+ if (resultType !== "upload_required" || typeof requestState !== "string") throw new Error("Unexpected result");
59
+ await uploadFiles(uploads, signal); // the host checks the targets and sends the bytes
60
+ return { requestState };
61
+ },
62
+ });
63
+ ```
64
+
65
+ `listen(filter)` opens a `subscriptions/listen` stream, which such servers need to send notifications such as `notifications/tools/list_changed` to `onNotification` listeners. It resolves once the server acknowledged the stream, with the notification types it agreed to; `closed` settles when the stream ends and `close()` ends it.
66
+
67
+ ### Stdio servers started elsewhere
68
+
69
+ `PipeTransport` speaks MCP's stdio framing over a program that something else starts, for example on another machine. `open` starts the program, connects its stdout and stderr to the given handlers, and returns an `McpPipe` (`write`, `closeStdin`, `close` to kill, and an `exited` promise). Any launcher that returns one works; a local spawn looks like this:
70
+
71
+ ```typescript
72
+ import { spawn } from "node:child_process";
73
+ import { PipeTransport } from "@dev-crowagent/pigeon-mcp";
74
+ import type { McpPipe, McpPipeHandlers } from "@dev-crowagent/pigeon-mcp";
75
+
76
+ function spawnPipe(argv: readonly string[], handlers: McpPipeHandlers): Promise<McpPipe> {
77
+ const [command, ...args] = argv;
78
+ const child = spawn(command, args, { stdio: "pipe" });
79
+ child.stdout.on("data", handlers.onStdout);
80
+ child.stderr.on("data", handlers.onStderr);
81
+ child.stdin.on("error", () => {});
82
+ const exited = new Promise<number | null>((resolve) => child.once("close", resolve));
83
+ return new Promise((resolve, reject) => {
84
+ child.once("error", reject);
85
+ child.once("spawn", () =>
86
+ resolve({
87
+ write: (data) => child.stdin.write(data),
88
+ closeStdin: () => child.stdin.end(),
89
+ close: () => child.kill("SIGKILL"),
90
+ exited,
91
+ }),
92
+ );
93
+ });
94
+ }
95
+
96
+ const transport = new PipeTransport({
97
+ open: (handlers) => spawnPipe(["my-server", "--stdio"], handlers),
98
+ });
99
+ await client.connect(transport);
100
+ ```
101
+
102
+ Closing the transport closes the program's stdin and kills it if it has not exited after `closeTimeoutMs` (default 2000). The transport closes when the program ends.
103
+
104
+ ### Tools for an LLM
105
+
106
+ `toLlmContent(result)` converts a `CallToolResult` to text and image content for a model, in the shape of `@dev-crowagent/pigeon-ai`'s `TextContent` and `ImageContent`. Text and images pass through, embedded text and image resources are unwrapped, and audio, resource links, and binary resources become short text placeholders. A result without content blocks but with `structuredContent` becomes its JSON.
107
+
108
+ Wrapping an MCP tool as a `pigeon-agent-core` `AgentTool`:
109
+
110
+ ```typescript
111
+ import type { AgentTool } from "@dev-crowagent/pigeon-agent-core";
112
+ import { toLlmContent } from "@dev-crowagent/pigeon-mcp";
113
+
114
+ const tools: AgentTool[] = (await client.listTools()).map((tool) => ({
115
+ // Providers allow at most 64 characters of [A-Za-z0-9_-].
116
+ name: `mcp_${tool.name}`.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64),
117
+ label: tool.title ?? tool.name,
118
+ description: tool.description ?? tool.name,
119
+ // Providers require an object schema, and some reject one without `properties`.
120
+ parameters: { ...tool.inputSchema, type: "object", properties: tool.inputSchema.properties ?? {} },
121
+ execute: async (_toolCallId, params, signal) => {
122
+ const result = await client.callTool(tool.name, params as Record<string, unknown>, { signal });
123
+ // MCP reports tool failures in the result instead of as a protocol error.
124
+ return { content: toLlmContent(result), details: undefined, isError: result.isError === true };
125
+ },
126
+ }));
127
+ ```
128
+
129
+ For applications that name tools like pigeon's coding agent: `createMcpToolName(server, tool, isTaken)` builds `mcp__<server>__<tool>`, limited to the characters and the 64-character length providers accept, with a hash suffix for long names and for names `isTaken` reports as used by another tool. `mcpNamespace(server)` is the prefix of a server's tool names. `normalizeMcpInputSchema()` turns an input schema into an object schema with `properties`, and `limitMcpContent(content, saveOutput)` keeps model-facing text within `MCP_OUTPUT_MAX_BYTES` (20KB) by cutting its middle; `saveOutput`, when given, stores the full text and returns the path the model can read it from. `toMcpModelContent(server, result, { saveOutput, readResourceTool })` converts a result's blocks for the model as pigeon does: text blobs as text, binary resources saved through `saveOutput`, and resource links naming `readResourceTool`. `createMcpResultSchema(tool.outputSchema)` is the output schema for programs (such as code mode scripts) that get a tool's whole `CallToolResult`, with the tool's own output schema as `structuredContent`.
130
+
131
+ The [mcp-codemode example](https://github.com/pooraddyy/pigeon/tree/main/packages/agent/examples/mcp-codemode) also forwards progress, passes `structuredContent` through, and lets `@dev-crowagent/pigeon-codemode` scripts call the tools.
132
+
133
+ ### OAuth
134
+
135
+ `@dev-crowagent/pigeon-mcp/oauth` provides the MCP OAuth client subset without depending on the official SDK:
136
+
137
+ ```typescript
138
+ import { McpClient, StreamableHttpTransport } from "@dev-crowagent/pigeon-mcp";
139
+ import {
140
+ adaptOAuthProvider,
141
+ authorizeMcp,
142
+ McpOAuthAuthorizationRequiredError,
143
+ McpOAuthProvider,
144
+ OAuthCallbackServer,
145
+ } from "@dev-crowagent/pigeon-mcp/oauth";
146
+
147
+ const serverUrl = "https://mcp.example.com/mcp";
148
+ const callback = await OAuthCallbackServer.listen();
149
+ let authorizationUrl: URL | undefined;
150
+ const oauth = new McpOAuthProvider({
151
+ serverUrl,
152
+ redirectUrl: callback.redirectUrl,
153
+ clientMetadata: { client_name: "My MCP client" },
154
+ onRedirect: (url) => {
155
+ authorizationUrl = url;
156
+ },
157
+ });
158
+
159
+ const connect = () => {
160
+ const client = new McpClient({ name: "my-client", version: "1.0.0" });
161
+ return {
162
+ client,
163
+ connected: client.connect(
164
+ new StreamableHttpTransport({ url: serverUrl, authProvider: adaptOAuthProvider(oauth) }),
165
+ ),
166
+ };
167
+ };
168
+
169
+ const first = connect();
170
+ try {
171
+ await first.connected;
172
+ } catch (error) {
173
+ if (!(error instanceof McpOAuthAuthorizationRequiredError)) throw error;
174
+ const state = await oauth.state();
175
+ const result = callback.waitForCallback(state);
176
+ // Open authorizationUrl in the user's browser here.
177
+ const { code } = await result;
178
+ await authorizeMcp(oauth, { serverUrl, authorizationCode: code });
179
+ }
180
+
181
+ const { client, connected } = connect();
182
+ await connected;
183
+ ```
184
+
185
+ Inject `McpOAuthStateStore` into `McpOAuthProvider` for durable credentials. The package does not open a browser or choose where credentials are stored.
186
+
187
+ #### Sign-in in two halves
188
+
189
+ `startMcpSignIn()` and `completeMcpSignIn()` run the sign-in pigeon uses, split so the second half can run in another request with the same state store (an `McpOAuthServerStore`: a state store with a refresh lock). The caller picks the redirect URI: a loopback one, or an https callback route of its own. `startMcpSignIn()` first tries to refresh the stored tokens under the store's refresh lock, so never call it while holding that lock; its `redirect` result is plain data the application can persist until the response arrives. Pass `completeMcpSignIn()` the same options, including the redirect URI you chose (not `started.redirectUrl`, which may be a variant specific to the MCP server).
190
+
191
+ ```typescript
192
+ import { completeMcpSignIn, responseFromRedirectUrl, startMcpSignIn } from "@dev-crowagent/pigeon-mcp/oauth";
193
+
194
+ const signIn = { serverUrl, store, settings: {}, redirectUrl: "https://app.example/mcp/callback", clientName: "My app" };
195
+ const started = await startMcpSignIn(signIn);
196
+ if (started.kind === "redirect") {
197
+ // Send the browser to started.authorizationUrl; keep `started` until the response arrives.
198
+ // Later, a callback route builds { code, state, iss } from its query; a pasted URL goes through:
199
+ const response = responseFromRedirectUrl(pastedUrl, started);
200
+ await completeMcpSignIn({ ...signIn, authorization: started, response });
201
+ }
202
+ ```
203
+
204
+ For a browser on the same machine, `listenForLoopbackSignIn()` starts a loopback callback server and returns its redirect URI, and `waitForLoopbackSignIn()` waits for the response on it or for a pasted redirect URL. `clientMetadataDocuments` lets authorization servers that support Client ID Metadata Documents identify the application by a document it publishes instead of registering a client. `createMcpAuthProvider()` is the matching `AuthProvider` for connections: it refreshes the stored tokens and throws `McpOAuthAuthorizationRequiredError` when the user has to sign in.
205
+
206
+ The OAuth implementation is adapted from the MIT-licensed Model Context Protocol TypeScript SDK v1.29.0. Its license is included under `THIRD_PARTY_NOTICES/`.
207
+
208
+ ### Configuration
209
+
210
+ `validateMcpServerConfig(name, entry, options)` validates one entry of the `mcpServers` shape that MCP clients share: stdio servers (`command`, `args`, `env`, `cwd`), Streamable HTTP servers (`url`, `headers`, `oauth`), and `enabled`, `description`, `timeout`, and `protocol`. It returns `{ kind: "stdio" | "http", config }` or `{ kind: "invalid", error }`. Fields it does not know stay in `config`, typed `unknown`, for the application to check afterwards, depending on `kind` where it matters. Resolving `${VAR}` references and relative paths is left to the application. `oauth.clientRegistration: "cimd"` is accepted only with `options.checkMetadataDocumentCallback`, which checks that the application's Client ID Metadata Documents list the callback.
211
+
212
+ ```typescript
213
+ import { validateMcpServerConfig } from "@dev-crowagent/pigeon-mcp";
214
+
215
+ for (const [name, entry] of Object.entries(file.mcpServers)) {
216
+ const result = validateMcpServerConfig(name, entry);
217
+ if (result.kind === "invalid") errors.push(result.error);
218
+ else if (result.config.shared !== undefined && typeof result.config.shared !== "boolean") {
219
+ errors.push(`server "${name}": shared must be a boolean`);
220
+ } else servers.set(name, result);
221
+ }
222
+ ```
223
+
224
+ `isMcpServerOverride(entry)` is true for entries without `command`, `url`, or `type`, which applications treat as overriding a few fields of a server defined in another file.
225
+
226
+ `@dev-crowagent/pigeon-mcp/config-schema` has the same shape as a JSON Schema, built with [`@dev-crowagent/pigeon-schema`](../schema/README.md); the config types above are derived from it. `McpStdioServerSchema` and `McpHttpServerSchema` are closed entry schemas, for example for an editor schema of a config file. An application that adds fields of its own builds its entries from the property maps (`mcpStdioServerProperties`, `mcpHttpServerProperties`, `mcpServerBaseProperties`, `mcpOAuthProperties`) with the same pigeon-schema copy. It does not express the cross-field rules (transport selection, port agreement, `cimd`): `validateMcpServerConfig` stays the check for loaded files.
227
+
228
+ ```typescript
229
+ import { mcpServerBaseProperties, mcpStdioServerProperties } from "@dev-crowagent/pigeon-mcp/config-schema";
230
+ import { bool, obj, opt } from "@dev-crowagent/pigeon-schema";
231
+
232
+ const StdioEntrySchema = obj({ ...mcpStdioServerProperties, ...mcpServerBaseProperties, shared: opt(bool()) });
233
+ ```
234
+
235
+ ## Supported protocol surface
236
+
237
+ - MCP protocol version `2025-11-25`, accepting servers that negotiate `2025-06-18`, `2025-03-26`, or `2024-11-05`
238
+ - the stateless revision `2026-07-28` for servers that reject `initialize` (see [Protocol versions](#protocol-versions)), with `server/discover`, multi round-trip requests, and the `Mcp-*` HTTP headers
239
+ - initialization and `notifications/initialized`
240
+ - ping
241
+ - paginated `tools/list`
242
+ - `tools/call`, including structured content
243
+ - progress notifications and timeout renewal
244
+ - request cancellation
245
+ - Streamable HTTP sessions, the server-to-client GET stream with reconnection, and resumption of dropped response streams with `Last-Event-ID`
246
+ - stdio shutdown per the spec (close stdin, then SIGTERM, then SIGKILL), applied to the server's whole process group
247
+ - stdio over a caller-provided pipe (`PipeTransport`)
248
+ - server `ping` and `roots/list` requests
249
+ - logging and tool-list-change notifications through the generic notification API
250
+ - OAuth protected-resource and authorization-server discovery
251
+ - PKCE authorization code flow, dynamic client registration, token refresh (one refresh shared by concurrent 401s), and step-up authorization for `insufficient_scope`
252
+
253
+ Batch JSON-RPC messages, legacy HTTP+SSE, servers, sampling, and tasks are outside the initial core.
254
+
255
+ ## Testing
256
+
257
+ `@dev-crowagent/pigeon-mcp/testing` exports `createInMemoryTransportPair()` for client and adapter tests.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Anthropic, PBC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,19 @@
1
+ export type McpFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
2
+ export interface UnauthorizedContext {
3
+ /** The 401 response, or a 403 response whose challenge reports `insufficient_scope`. */
4
+ response: Response;
5
+ serverUrl: URL;
6
+ fetch: McpFetch;
7
+ /** Access token the rejected request carried, if any. A different current token means another request already refreshed it. */
8
+ token?: string;
9
+ }
10
+ /** Supplies bearer tokens to an MCP HTTP transport and may refresh them after a 401 response. */
11
+ export interface AuthProvider {
12
+ /**
13
+ * Token for the next request. May refresh it over the network first, so the transport calls it only
14
+ * before requests whose answer it waits for. Closing a session reuses the token of the last request.
15
+ */
16
+ token(): Promise<string | undefined>;
17
+ onUnauthorized?(context: UnauthorizedContext): Promise<void>;
18
+ }
19
+ //# sourceMappingURL=auth-provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-provider.d.ts","sourceRoot":"","sources":["../src/auth-provider.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,QAAQ,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEtF,MAAM,WAAW,mBAAmB;IACnC,wFAAwF;IACxF,QAAQ,EAAE,QAAQ,CAAC;IACnB,SAAS,EAAE,GAAG,CAAC;IACf,KAAK,EAAE,QAAQ,CAAC;IAChB,+HAA+H;IAC/H,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,iGAAiG;AACjG,MAAM,WAAW,YAAY;IAC5B;;;OAGG;IACH,KAAK,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IACrC,cAAc,CAAC,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7D"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=auth-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-provider.js","sourceRoot":"","sources":["../src/auth-provider.ts"],"names":[],"mappings":"","sourcesContent":["export type McpFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface UnauthorizedContext {\n\t/** The 401 response, or a 403 response whose challenge reports `insufficient_scope`. */\n\tresponse: Response;\n\tserverUrl: URL;\n\tfetch: McpFetch;\n\t/** Access token the rejected request carried, if any. A different current token means another request already refreshed it. */\n\ttoken?: string;\n}\n\n/** Supplies bearer tokens to an MCP HTTP transport and may refresh them after a 401 response. */\nexport interface AuthProvider {\n\t/**\n\t * Token for the next request. May refresh it over the network first, so the transport calls it only\n\t * before requests whose answer it waits for. Closing a session reuses the token of the last request.\n\t */\n\ttoken(): Promise<string | undefined>;\n\tonUnauthorized?(context: UnauthorizedContext): Promise<void>;\n}\n"]}