@diffra-ai/mcp 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +7 -0
- package/LICENSE +22 -0
- package/README.md +190 -2
- package/THIRD_PARTY_NOTICES/modelcontextprotocol-typescript-sdk.txt +21 -0
- package/dist/auth-provider.d.ts +19 -0
- package/dist/auth-provider.d.ts.map +1 -0
- package/dist/auth-provider.js +2 -0
- package/dist/auth-provider.js.map +1 -0
- package/dist/client.d.ts +89 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +461 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +117 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +153 -0
- package/dist/config.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/input-schema.d.ts +7 -0
- package/dist/input-schema.d.ts.map +1 -0
- package/dist/input-schema.js +13 -0
- package/dist/input-schema.js.map +1 -0
- package/dist/model-content.d.ts +19 -0
- package/dist/model-content.d.ts.map +1 -0
- package/dist/model-content.js +67 -0
- package/dist/model-content.js.map +1 -0
- package/dist/naming.d.ts +23 -0
- package/dist/naming.d.ts.map +1 -0
- package/dist/naming.js +37 -0
- package/dist/naming.js.map +1 -0
- package/dist/oauth/auth-provider.d.ts +52 -0
- package/dist/oauth/auth-provider.d.ts.map +1 -0
- package/dist/oauth/auth-provider.js +97 -0
- package/dist/oauth/auth-provider.js.map +1 -0
- package/dist/oauth/callback.d.ts +48 -0
- package/dist/oauth/callback.d.ts.map +1 -0
- package/dist/oauth/callback.js +119 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/client-settings.d.ts +107 -0
- package/dist/oauth/client-settings.d.ts.map +1 -0
- package/dist/oauth/client-settings.js +114 -0
- package/dist/oauth/client-settings.js.map +1 -0
- package/dist/oauth/discovery.d.ts +30 -0
- package/dist/oauth/discovery.d.ts.map +1 -0
- package/dist/oauth/discovery.js +156 -0
- package/dist/oauth/discovery.js.map +1 -0
- package/dist/oauth/errors.d.ts +32 -0
- package/dist/oauth/errors.d.ts.map +1 -0
- package/dist/oauth/errors.js +58 -0
- package/dist/oauth/errors.js.map +1 -0
- package/dist/oauth/flow.d.ts +112 -0
- package/dist/oauth/flow.d.ts.map +1 -0
- package/dist/oauth/flow.js +360 -0
- package/dist/oauth/flow.js.map +1 -0
- package/dist/oauth/index.d.ts +11 -0
- package/dist/oauth/index.d.ts.map +1 -0
- package/dist/oauth/index.js +9 -0
- package/dist/oauth/index.js.map +1 -0
- package/dist/oauth/loopback.d.ts +51 -0
- package/dist/oauth/loopback.d.ts.map +1 -0
- package/dist/oauth/loopback.js +98 -0
- package/dist/oauth/loopback.js.map +1 -0
- package/dist/oauth/provider.d.ts +62 -0
- package/dist/oauth/provider.d.ts.map +1 -0
- package/dist/oauth/provider.js +118 -0
- package/dist/oauth/provider.js.map +1 -0
- package/dist/oauth/sign-in.d.ts +73 -0
- package/dist/oauth/sign-in.d.ts.map +1 -0
- package/dist/oauth/sign-in.js +182 -0
- package/dist/oauth/sign-in.js.map +1 -0
- package/dist/oauth/types.d.ts +83 -0
- package/dist/oauth/types.d.ts.map +1 -0
- package/dist/oauth/types.js +113 -0
- package/dist/oauth/types.js.map +1 -0
- package/dist/output-limit.d.ts +24 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +58 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/protocol/content.d.ts +83 -0
- package/dist/protocol/content.d.ts.map +1 -0
- package/dist/protocol/content.js +41 -0
- package/dist/protocol/content.js.map +1 -0
- package/dist/protocol/jsonrpc.d.ts +59 -0
- package/dist/protocol/jsonrpc.d.ts.map +1 -0
- package/dist/protocol/jsonrpc.js +67 -0
- package/dist/protocol/jsonrpc.js.map +1 -0
- package/dist/protocol/types.d.ts +123 -0
- package/dist/protocol/types.d.ts.map +1 -0
- package/dist/protocol/types.js +7 -0
- package/dist/protocol/types.js.map +1 -0
- package/dist/result-schema.d.ts +10 -0
- package/dist/result-schema.d.ts.map +1 -0
- package/dist/result-schema.js +78 -0
- package/dist/result-schema.js.map +1 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +2 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/transports/in-memory.d.ts +19 -0
- package/dist/transports/in-memory.d.ts.map +1 -0
- package/dist/transports/in-memory.js +50 -0
- package/dist/transports/in-memory.js.map +1 -0
- package/dist/transports/lines.d.ts +34 -0
- package/dist/transports/lines.d.ts.map +1 -0
- package/dist/transports/lines.js +85 -0
- package/dist/transports/lines.js.map +1 -0
- package/dist/transports/pipe.d.ts +49 -0
- package/dist/transports/pipe.d.ts.map +1 -0
- package/dist/transports/pipe.js +96 -0
- package/dist/transports/pipe.js.map +1 -0
- package/dist/transports/stdio.d.ts +29 -0
- package/dist/transports/stdio.d.ts.map +1 -0
- package/dist/transports/stdio.js +170 -0
- package/dist/transports/stdio.js.map +1 -0
- package/dist/transports/streamable-http.d.ts +103 -0
- package/dist/transports/streamable-http.d.ts.map +1 -0
- package/dist/transports/streamable-http.js +531 -0
- package/dist/transports/streamable-http.js.map +1 -0
- package/dist/transports/transport.d.ts +36 -0
- package/dist/transports/transport.d.ts.map +1 -0
- package/dist/transports/transport.js +38 -0
- package/dist/transports/transport.js.map +1 -0
- package/package.json +59 -5
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- First diffra release, forked from pi at [earendil-works/pi@780bf31](https://github.com/earendil-works/pi/tree/780bf31fcaeb252fa9b68df3964c735eae75bde3). Earlier history is in [pi's changelog for this package](https://github.com/earendil-works/pi/blob/780bf31fcaeb252fa9b68df3964c735eae75bde3/packages/mcp/CHANGELOG.md).
|
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Mario Zechner
|
|
4
|
+
Copyright (c) 2026 DingxinTao0417
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,191 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @diffra-ai/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small, standalone Model Context Protocol client. It does not depend on the official MCP SDK or other diffra 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 "@diffra-ai/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
|
+
### Stdio servers started elsewhere
|
|
33
|
+
|
|
34
|
+
`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). `@diffra-ai/env`'s `openProcess()` returns one, without an adapter:
|
|
35
|
+
|
|
36
|
+
```typescript
|
|
37
|
+
import { openProcess } from "@diffra-ai/env";
|
|
38
|
+
import { PipeTransport } from "@diffra-ai/mcp";
|
|
39
|
+
|
|
40
|
+
const transport = new PipeTransport({
|
|
41
|
+
open: (handlers) => openProcess(connection, { cwd, argv, ...handlers }),
|
|
42
|
+
});
|
|
43
|
+
await client.connect(transport);
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
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.
|
|
47
|
+
|
|
48
|
+
### Tools for an LLM
|
|
49
|
+
|
|
50
|
+
`toLlmContent(result)` converts a `CallToolResult` to text and image content for a model, in the shape of `@diffra-ai/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.
|
|
51
|
+
|
|
52
|
+
Wrapping an MCP tool as a `diffra-agent-core` `AgentTool`:
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
import type { AgentTool } from "@diffra-ai/agent-core";
|
|
56
|
+
import { toLlmContent } from "@diffra-ai/mcp";
|
|
57
|
+
|
|
58
|
+
const tools: AgentTool[] = (await client.listTools()).map((tool) => ({
|
|
59
|
+
// Providers allow at most 64 characters of [A-Za-z0-9_-].
|
|
60
|
+
name: `mcp_${tool.name}`.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 64),
|
|
61
|
+
label: tool.title ?? tool.name,
|
|
62
|
+
description: tool.description ?? tool.name,
|
|
63
|
+
// Providers require an object schema, and some reject one without `properties`.
|
|
64
|
+
parameters: { ...tool.inputSchema, type: "object", properties: tool.inputSchema.properties ?? {} },
|
|
65
|
+
execute: async (_toolCallId, params, signal) => {
|
|
66
|
+
const result = await client.callTool(tool.name, params as Record<string, unknown>, { signal });
|
|
67
|
+
// MCP reports tool failures in the result instead of as a protocol error.
|
|
68
|
+
return { content: toLlmContent(result), details: undefined, isError: result.isError === true };
|
|
69
|
+
},
|
|
70
|
+
}));
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
For applications that name tools like diffra'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 diffra 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`.
|
|
74
|
+
|
|
75
|
+
The [mcp-codemode example](https://github.com/DingxinTao0417/diffra-cli/tree/main/packages/agent/examples/mcp-codemode) also forwards progress, passes `structuredContent` through, and lets `@diffra-ai/codemode` scripts call the tools.
|
|
76
|
+
|
|
77
|
+
### OAuth
|
|
78
|
+
|
|
79
|
+
`@diffra-ai/mcp/oauth` provides the MCP OAuth client subset without depending on the official SDK:
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import { McpClient, StreamableHttpTransport } from "@diffra-ai/mcp";
|
|
83
|
+
import {
|
|
84
|
+
adaptOAuthProvider,
|
|
85
|
+
authorizeMcp,
|
|
86
|
+
McpOAuthAuthorizationRequiredError,
|
|
87
|
+
McpOAuthProvider,
|
|
88
|
+
OAuthCallbackServer,
|
|
89
|
+
} from "@diffra-ai/mcp/oauth";
|
|
90
|
+
|
|
91
|
+
const serverUrl = "https://mcp.example.com/mcp";
|
|
92
|
+
const callback = await OAuthCallbackServer.listen();
|
|
93
|
+
let authorizationUrl: URL | undefined;
|
|
94
|
+
const oauth = new McpOAuthProvider({
|
|
95
|
+
serverUrl,
|
|
96
|
+
redirectUrl: callback.redirectUrl,
|
|
97
|
+
clientMetadata: { client_name: "My MCP client" },
|
|
98
|
+
onRedirect: (url) => {
|
|
99
|
+
authorizationUrl = url;
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const connect = () => {
|
|
104
|
+
const client = new McpClient({ name: "my-client", version: "1.0.0" });
|
|
105
|
+
return {
|
|
106
|
+
client,
|
|
107
|
+
connected: client.connect(
|
|
108
|
+
new StreamableHttpTransport({ url: serverUrl, authProvider: adaptOAuthProvider(oauth) }),
|
|
109
|
+
),
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const first = connect();
|
|
114
|
+
try {
|
|
115
|
+
await first.connected;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (!(error instanceof McpOAuthAuthorizationRequiredError)) throw error;
|
|
118
|
+
const state = await oauth.state();
|
|
119
|
+
const result = callback.waitForCallback(state);
|
|
120
|
+
// Open authorizationUrl in the user's browser here.
|
|
121
|
+
const { code } = await result;
|
|
122
|
+
await authorizeMcp(oauth, { serverUrl, authorizationCode: code });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const { client, connected } = connect();
|
|
126
|
+
await connected;
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Inject `McpOAuthStateStore` into `McpOAuthProvider` for durable credentials. The package does not open a browser or choose where credentials are stored.
|
|
130
|
+
|
|
131
|
+
#### Sign-in in two halves
|
|
132
|
+
|
|
133
|
+
`startMcpSignIn()` and `completeMcpSignIn()` run the sign-in diffra 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).
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
import { completeMcpSignIn, responseFromRedirectUrl, startMcpSignIn } from "@diffra-ai/mcp/oauth";
|
|
137
|
+
|
|
138
|
+
const signIn = { serverUrl, store, settings: {}, redirectUrl: "https://app.example/mcp/callback", clientName: "My app" };
|
|
139
|
+
const started = await startMcpSignIn(signIn);
|
|
140
|
+
if (started.kind === "redirect") {
|
|
141
|
+
// Send the browser to started.authorizationUrl; keep `started` until the response arrives.
|
|
142
|
+
// Later, a callback route builds { code, state, iss } from its query; a pasted URL goes through:
|
|
143
|
+
const response = responseFromRedirectUrl(pastedUrl, started);
|
|
144
|
+
await completeMcpSignIn({ ...signIn, authorization: started, response });
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
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.
|
|
149
|
+
|
|
150
|
+
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/`.
|
|
151
|
+
|
|
152
|
+
### Configuration
|
|
153
|
+
|
|
154
|
+
`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`, and `timeout`. 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.
|
|
155
|
+
|
|
156
|
+
```typescript
|
|
157
|
+
import { validateMcpServerConfig } from "@diffra-ai/mcp";
|
|
158
|
+
|
|
159
|
+
for (const [name, entry] of Object.entries(file.mcpServers)) {
|
|
160
|
+
const result = validateMcpServerConfig(name, entry);
|
|
161
|
+
if (result.kind === "invalid") errors.push(result.error);
|
|
162
|
+
else if (result.config.shared !== undefined && typeof result.config.shared !== "boolean") {
|
|
163
|
+
errors.push(`server "${name}": shared must be a boolean`);
|
|
164
|
+
} else servers.set(name, result);
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`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.
|
|
169
|
+
|
|
170
|
+
## Supported protocol surface
|
|
171
|
+
|
|
172
|
+
- MCP protocol version `2025-11-25`, accepting servers that negotiate `2025-06-18`, `2025-03-26`, or `2024-11-05`
|
|
173
|
+
- initialization and `notifications/initialized`
|
|
174
|
+
- ping
|
|
175
|
+
- paginated `tools/list`
|
|
176
|
+
- `tools/call`, including structured content
|
|
177
|
+
- progress notifications and timeout renewal
|
|
178
|
+
- request cancellation
|
|
179
|
+
- Streamable HTTP sessions, the server-to-client GET stream with reconnection, and resumption of dropped response streams with `Last-Event-ID`
|
|
180
|
+
- stdio shutdown per the spec (close stdin, then SIGTERM, then SIGKILL), applied to the server's whole process group
|
|
181
|
+
- stdio over a caller-provided pipe (`PipeTransport`)
|
|
182
|
+
- server `ping` and `roots/list` requests
|
|
183
|
+
- logging and tool-list-change notifications through the generic notification API
|
|
184
|
+
- OAuth protected-resource and authorization-server discovery
|
|
185
|
+
- PKCE authorization code flow, dynamic client registration, token refresh (one refresh shared by concurrent 401s), and step-up authorization for `insufficient_scope`
|
|
186
|
+
|
|
187
|
+
Batch JSON-RPC messages, legacy HTTP+SSE, servers, sampling, and tasks are outside the initial core.
|
|
188
|
+
|
|
189
|
+
## Testing
|
|
190
|
+
|
|
191
|
+
`@diffra-ai/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 @@
|
|
|
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"]}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { CallToolResult } from "./protocol/content.ts";
|
|
2
|
+
import { type ClientCapabilities, type Implementation, type InitializeResult, type ListResourcesResult, type ListResourceTemplatesResult, type ProgressNotification, type ReadResourceResult, type Resource, type ResourceTemplate, type Root, type ServerCapabilities, type SupportedProtocolVersion, type Tool } from "./protocol/types.ts";
|
|
3
|
+
import type { McpTransport } from "./transports/transport.ts";
|
|
4
|
+
type ClientState = "idle" | "connecting" | "connected" | "closed";
|
|
5
|
+
type NotificationListener = (params: unknown) => void;
|
|
6
|
+
type ErrorListener = (error: Error) => void;
|
|
7
|
+
type CloseListener = () => void;
|
|
8
|
+
type RequestHandler = (params: unknown, context: {
|
|
9
|
+
signal: AbortSignal;
|
|
10
|
+
}) => unknown | Promise<unknown>;
|
|
11
|
+
export interface McpClientOptions extends Implementation {
|
|
12
|
+
capabilities?: ClientCapabilities;
|
|
13
|
+
protocolVersion?: SupportedProtocolVersion;
|
|
14
|
+
requestTimeoutMs?: number;
|
|
15
|
+
roots?: readonly Root[] | (() => readonly Root[] | Promise<readonly Root[]>);
|
|
16
|
+
}
|
|
17
|
+
export interface McpRequestOptions {
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
onProgress?: (progress: ProgressNotification) => void;
|
|
21
|
+
}
|
|
22
|
+
export declare class McpClient {
|
|
23
|
+
readonly options: Readonly<McpClientOptions>;
|
|
24
|
+
private state;
|
|
25
|
+
private transport;
|
|
26
|
+
private nextRequestId;
|
|
27
|
+
private serverInfoValue;
|
|
28
|
+
private serverCapabilitiesValue;
|
|
29
|
+
private instructionsValue;
|
|
30
|
+
private protocolVersionValue;
|
|
31
|
+
private pending;
|
|
32
|
+
private progressRequests;
|
|
33
|
+
private incoming;
|
|
34
|
+
private requestHandlers;
|
|
35
|
+
private notificationListeners;
|
|
36
|
+
private errorListeners;
|
|
37
|
+
private closeListeners;
|
|
38
|
+
private disposers;
|
|
39
|
+
constructor(options: McpClientOptions);
|
|
40
|
+
get connectionState(): ClientState;
|
|
41
|
+
get serverInfo(): Implementation | undefined;
|
|
42
|
+
get serverCapabilities(): ServerCapabilities | undefined;
|
|
43
|
+
get instructions(): string | undefined;
|
|
44
|
+
get protocolVersion(): string | undefined;
|
|
45
|
+
connect(transport: McpTransport): Promise<InitializeResult>;
|
|
46
|
+
request<Result = unknown>(method: string, params?: Record<string, unknown>, options?: McpRequestOptions): Promise<Result>;
|
|
47
|
+
notify(method: string, params?: Record<string, unknown>): Promise<void>;
|
|
48
|
+
setRequestHandler(method: string, handler: RequestHandler): () => void;
|
|
49
|
+
onNotification(method: string, listener: NotificationListener): () => void;
|
|
50
|
+
onError(listener: ErrorListener): () => void;
|
|
51
|
+
/** Called once when the connection closes, whether the transport dropped or `close()` was called. */
|
|
52
|
+
onClose(listener: CloseListener): () => void;
|
|
53
|
+
ping(options?: McpRequestOptions): Promise<void>;
|
|
54
|
+
listTools(options?: McpRequestOptions): Promise<Tool[]>;
|
|
55
|
+
/** Every resource, following `nextCursor` through all pages. */
|
|
56
|
+
listResources(options?: McpRequestOptions): Promise<Resource[]>;
|
|
57
|
+
/** One page of resources, starting at `cursor`. */
|
|
58
|
+
listResourcesPage(cursor?: string, options?: McpRequestOptions): Promise<ListResourcesResult>;
|
|
59
|
+
/** Every resource template, following `nextCursor` through all pages. */
|
|
60
|
+
listResourceTemplates(options?: McpRequestOptions): Promise<ResourceTemplate[]>;
|
|
61
|
+
/** One page of resource templates, starting at `cursor`. */
|
|
62
|
+
listResourceTemplatesPage(cursor?: string, options?: McpRequestOptions): Promise<ListResourceTemplatesResult>;
|
|
63
|
+
readResource(uri: string, options?: McpRequestOptions): Promise<ReadResourceResult>;
|
|
64
|
+
private listPage;
|
|
65
|
+
/** Every item of a paginated list method. */
|
|
66
|
+
private listAll;
|
|
67
|
+
callTool(name: string, args?: Record<string, unknown>, options?: McpRequestOptions): Promise<CallToolResult>;
|
|
68
|
+
close(): Promise<void>;
|
|
69
|
+
private requestInternal;
|
|
70
|
+
private notifyInternal;
|
|
71
|
+
private requireTransport;
|
|
72
|
+
private handleMessage;
|
|
73
|
+
private handleResponse;
|
|
74
|
+
private handleRequest;
|
|
75
|
+
private handleNotification;
|
|
76
|
+
private handleProgress;
|
|
77
|
+
private handleCancelled;
|
|
78
|
+
private armTimeout;
|
|
79
|
+
private cancelPending;
|
|
80
|
+
private removePending;
|
|
81
|
+
private rejectPending;
|
|
82
|
+
private handleTransportClose;
|
|
83
|
+
/** Idempotent: rejects in-flight requests, aborts server requests we are serving, and flips the state. */
|
|
84
|
+
private markClosed;
|
|
85
|
+
private emitError;
|
|
86
|
+
private disposeTransportListeners;
|
|
87
|
+
}
|
|
88
|
+
export {};
|
|
89
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAkB5D,OAAO,EACN,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EAErB,KAAK,mBAAmB,EACxB,KAAK,2BAA2B,EAChC,KAAK,oBAAoB,EACzB,KAAK,kBAAkB,EACvB,KAAK,QAAQ,EACb,KAAK,gBAAgB,EACrB,KAAK,IAAI,EACT,KAAK,kBAAkB,EAEvB,KAAK,wBAAwB,EAC7B,KAAK,IAAI,EACT,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAK9D,KAAK,WAAW,GAAG,MAAM,GAAG,YAAY,GAAG,WAAW,GAAG,QAAQ,CAAC;AAClE,KAAK,oBAAoB,GAAG,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI,CAAC;AACtD,KAAK,aAAa,GAAG,CAAC,KAAK,EAAE,KAAK,KAAK,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