@astratra/mcp 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +89 -2
- package/package.json +37 -4
- package/src/client.js +112 -0
- package/src/index.d.ts +103 -0
- package/src/index.js +6 -0
- package/src/jsonrpc.js +198 -0
- package/src/server.js +164 -0
- package/src/transports.js +476 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Astratra contributors
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @astratra/mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Le Model Context Protocol (MCP) sans dépendance : un **client** pour brancher une IA sur un serveur MCP, un
|
|
4
|
+
**serveur** pour offrir des outils à une IA, et les transports **stdio** et **Streamable HTTP**. Il remplace le SDK
|
|
5
|
+
officiel (`@modelcontextprotocol/sdk`, qui installe zod, express et une vingtaine d'autres paquets) pour ces usages,
|
|
6
|
+
et parle avec lui dans les deux sens.
|
|
7
|
+
|
|
8
|
+
## Un serveur d'outils
|
|
9
|
+
|
|
10
|
+
```js
|
|
11
|
+
const { createMcpServer, createStdioServerTransport } = require('@astratra/mcp');
|
|
12
|
+
|
|
13
|
+
const server = createMcpServer({ name: 'mes-outils', version: '1.0.0' }, { instructions: 'Outils de la boutique.' })
|
|
14
|
+
.tool({
|
|
15
|
+
name: 'stock',
|
|
16
|
+
description: 'Le stock d’un produit',
|
|
17
|
+
inputSchema: { type: 'object', properties: { sku: { type: 'string' } }, required: ['sku'], additionalProperties: false },
|
|
18
|
+
annotations: { readOnlyHint: true },
|
|
19
|
+
}, async ({ sku }, { signal }) => JSON.stringify(await lireStock(sku, { signal })));
|
|
20
|
+
|
|
21
|
+
await server.connect(createStdioServerTransport()); // un éditeur ou un assistant lance ce fichier
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Le texte rendu devient un résultat `{ content: [{ type: 'text', text }] }` ; un objet est rendu tel quel. Les
|
|
25
|
+
arguments sont vérifiés contre le schéma avant l'appel (objet, `required`, type et `enum` des propriétés) ; un
|
|
26
|
+
argument hors du schéma est retiré quand `additionalProperties` vaut `false`. Une exception de l'outil revient en
|
|
27
|
+
résultat `isError` avec un message générique : jamais le message de l'exception, qui peut contenir un chemin ou une
|
|
28
|
+
clé.
|
|
29
|
+
|
|
30
|
+
Pour une autre méthode : `server.setRequestHandler('resources/list', async (request, extra) => ({ … }))`. Une
|
|
31
|
+
`McpError(code, message)` garde son code et son message ; toute autre exception devient « Internal error ».
|
|
32
|
+
|
|
33
|
+
## En HTTP
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
const http = require('node:http');
|
|
37
|
+
const { createStreamableHttpHandler } = require('@astratra/mcp');
|
|
38
|
+
|
|
39
|
+
const handler = createStreamableHttpHandler({
|
|
40
|
+
createServer: () => creerMonServeur(), // un serveur neuf par session
|
|
41
|
+
allowedOrigins: ['https://app.exemple.fr'], // pages web permises (aucune par défaut)
|
|
42
|
+
});
|
|
43
|
+
http.createServer(handler).listen(3001); // ou app.post('/mcp', handler) avec Express
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
- **L'en-tête Origin est vérifié** : une page web ne peut pas parler au serveur sans être dans `allowedOrigins`
|
|
47
|
+
(protection contre le « DNS rebinding », exigée par la spécification ; le SDK ne la fait pas par défaut).
|
|
48
|
+
- Le corps fait 4 Mio au plus, un lot 100 messages au plus ; 1 000 sessions au plus, fermées après 30 minutes sans
|
|
49
|
+
requête (jamais pendant une requête) ; une requête plus longue que 5 minutes répond 504.
|
|
50
|
+
- Le serveur répond en JSON ; il n'ouvre pas de flux GET (rien n'est poussé au client hors des réponses).
|
|
51
|
+
|
|
52
|
+
## Un client
|
|
53
|
+
|
|
54
|
+
```js
|
|
55
|
+
const { createMcpClient, createStreamableHttpClientTransport } = require('@astratra/mcp');
|
|
56
|
+
|
|
57
|
+
const client = createMcpClient({ name: 'mon-app', version: '1.0.0' });
|
|
58
|
+
await client.connect(createStreamableHttpClientTransport('https://mcp.exemple.fr/mcp', { headers: { Authorization: `Bearer ${cle}` } }));
|
|
59
|
+
|
|
60
|
+
const outils = await client.listAllTools();
|
|
61
|
+
const resultat = await client.callTool({ name: 'stock', arguments: { sku: 'A12' } }, { timeoutMs: 20_000, signal });
|
|
62
|
+
await client.close(); // ferme aussi la session chez le serveur
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- L'adresse doit être en https:// (http:// seulement vers la machine), sans identifiants (la clé va dans les
|
|
66
|
+
en-têtes) ; aucune redirection n'est suivie.
|
|
67
|
+
- Une réponse fait 4 Mio au plus, un flux SSE 16 Mio au plus ; un flux qui casse fait échouer sa requête tout de
|
|
68
|
+
suite.
|
|
69
|
+
- Un appel trop long est abandonné et le serveur est prévenu (`notifications/cancelled`) ; un `signal` annule de la
|
|
70
|
+
même façon.
|
|
71
|
+
- `listAllTools` s'arrête si un serveur renvoie deux fois le même curseur.
|
|
72
|
+
|
|
73
|
+
Le client répond lui-même aux requêtes `ping` du serveur et refuse les autres (ni sampling, ni elicitation, ni
|
|
74
|
+
roots).
|
|
75
|
+
|
|
76
|
+
## Avec le SDK officiel
|
|
77
|
+
|
|
78
|
+
Les transports ont la même forme que ceux du SDK (`start`, `send`, `close`, `onmessage`…) : un transport du SDK se
|
|
79
|
+
branche sur ce client ou ce serveur, et le client du SDK parle à ce serveur (HTTP, stdio, mémoire). Les essais le
|
|
80
|
+
vérifient avec `MCP_SDK_PROJECT=/chemin/vers/un/projet` qui a installé le SDK.
|
|
81
|
+
|
|
82
|
+
## Tests
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
npm test --workspace @astratra/mcp
|
|
86
|
+
npm run verify:mutations --workspace @astratra/mcp # 22 mutations
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Les réponses du serveur, du transport HTTP et les messages du client sont comparés au SDK 1.32.2, enregistré une
|
|
90
|
+
fois (`scripts/record-sdk-reference.cjs`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/mcp",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "The Model Context Protocol with no dependency: client and server (initialize, tools/list, tools/call, ping, cancellation), stdio and Streamable HTTP transports, Origin check, size and time limits. Works with transports from the official SDK too.",
|
|
5
|
+
"engines": {
|
|
6
|
+
"node": ">=22"
|
|
7
|
+
},
|
|
8
|
+
"main": "src/index.js",
|
|
9
|
+
"types": "src/index.d.ts",
|
|
10
|
+
"type": "commonjs",
|
|
11
|
+
"files": [
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"test": "jest",
|
|
16
|
+
"verify:mutations": "node scripts/verify-mcp-mutations.cjs"
|
|
17
|
+
},
|
|
18
|
+
"jest": {
|
|
19
|
+
"testMatch": [
|
|
20
|
+
"**/__tests__/**/*.test.js"
|
|
21
|
+
]
|
|
22
|
+
},
|
|
23
|
+
"keywords": [
|
|
24
|
+
"astratra",
|
|
25
|
+
"mcp",
|
|
26
|
+
"model-context-protocol",
|
|
27
|
+
"json-rpc",
|
|
28
|
+
"streamable-http",
|
|
29
|
+
"stdio"
|
|
30
|
+
],
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@astratra/testkit": "^2.0.0",
|
|
37
|
+
"jest": "30.4.2"
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
const { createSession, McpError, ErrorCode, LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS } = require('./jsonrpc');
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Un client MCP : la poignée de main (initialize puis notifications/initialized), la liste des outils page après
|
|
5
|
+
* page, l'appel d'un outil avec délai et annulation, ping. Il remplace Client du SDK pour ces usages.
|
|
6
|
+
*
|
|
7
|
+
* Le client ne sert aucune requête du serveur (ni sampling, ni elicitation, ni roots) : il n'en annonce pas la
|
|
8
|
+
* capacité, et répond « Method not found » à une requête que le serveur enverrait quand même, sauf ping.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {object} [info] { name, version } annoncés au serveur
|
|
15
|
+
* @param {object} [options] { capabilities, timeoutMs (défaut 60 s par requête) }
|
|
16
|
+
*/
|
|
17
|
+
function createMcpClient(info = { name: 'astratra-mcp', version: '1.0.0' }, options = {}) {
|
|
18
|
+
const timeoutMs = options.timeoutMs ?? 60_000;
|
|
19
|
+
let session = null;
|
|
20
|
+
let serverInfo = null;
|
|
21
|
+
let serverCapabilities = null;
|
|
22
|
+
let instructions = null;
|
|
23
|
+
let protocolVersion = null;
|
|
24
|
+
|
|
25
|
+
const client = {
|
|
26
|
+
async connect(transport, { timeoutMs: connectTimeout = timeoutMs } = {}) {
|
|
27
|
+
if (session) throw new Error('already connected');
|
|
28
|
+
session = createSession({
|
|
29
|
+
onRequest: async (request) => {
|
|
30
|
+
if (request.method === 'ping') return {};
|
|
31
|
+
throw new McpError(ErrorCode.MethodNotFound, 'Method not found');
|
|
32
|
+
},
|
|
33
|
+
onError: (error) => client.onerror?.(error),
|
|
34
|
+
onClose: () => client.onclose?.(),
|
|
35
|
+
});
|
|
36
|
+
await session.connect(transport);
|
|
37
|
+
try {
|
|
38
|
+
const result = await session.request('initialize', { protocolVersion: LATEST_PROTOCOL_VERSION, capabilities: options.capabilities || {}, clientInfo: { name: info.name, version: info.version } }, { timeoutMs: connectTimeout });
|
|
39
|
+
if (!isPlainObject(result) || !SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) throw new Error(`Server's protocol version is not supported: ${isPlainObject(result) ? String(result.protocolVersion).slice(0, 40) : 'none'}`);
|
|
40
|
+
protocolVersion = result.protocolVersion;
|
|
41
|
+
serverInfo = isPlainObject(result.serverInfo) ? result.serverInfo : null;
|
|
42
|
+
serverCapabilities = isPlainObject(result.capabilities) ? result.capabilities : {};
|
|
43
|
+
instructions = typeof result.instructions === 'string' ? result.instructions : null;
|
|
44
|
+
if (typeof transport.setProtocolVersion === 'function') transport.setProtocolVersion(protocolVersion);
|
|
45
|
+
await session.notify('notifications/initialized');
|
|
46
|
+
} catch (error) {
|
|
47
|
+
await client.close();
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
/** Une page d'outils : { tools, nextCursor }. */
|
|
53
|
+
async listTools(params = {}, requestOptions = {}) {
|
|
54
|
+
if (!serverCapabilities?.tools) throw new McpError(ErrorCode.MethodNotFound, 'Server does not support tools');
|
|
55
|
+
const result = await session.request('tools/list', params.cursor === undefined ? undefined : { cursor: params.cursor }, { timeoutMs, ...requestOptions });
|
|
56
|
+
if (!isPlainObject(result) || !Array.isArray(result.tools)) throw new McpError(ErrorCode.InvalidRequest, 'Invalid tools/list result');
|
|
57
|
+
return { tools: result.tools.filter((t) => isPlainObject(t) && typeof t.name === 'string'), ...(typeof result.nextCursor === 'string' ? { nextCursor: result.nextCursor } : {}) };
|
|
58
|
+
},
|
|
59
|
+
|
|
60
|
+
/** Tous les outils, page après page (au plus maxPages, 100 par défaut ; un curseur qui se répète arrête la boucle). */
|
|
61
|
+
async listAllTools({ maxPages = 100, ...requestOptions } = {}) {
|
|
62
|
+
const all = [];
|
|
63
|
+
const seen = new Set();
|
|
64
|
+
let cursor;
|
|
65
|
+
for (let page = 0; page < maxPages; page++) {
|
|
66
|
+
const result = await client.listTools(cursor === undefined ? {} : { cursor }, requestOptions);
|
|
67
|
+
all.push(...result.tools);
|
|
68
|
+
cursor = result.nextCursor;
|
|
69
|
+
if (cursor === undefined) return all;
|
|
70
|
+
if (seen.has(cursor)) throw new McpError(ErrorCode.InvalidRequest, 'tools/list returned the same cursor twice');
|
|
71
|
+
seen.add(cursor);
|
|
72
|
+
}
|
|
73
|
+
throw new McpError(ErrorCode.InvalidRequest, `tools/list has more than ${maxPages} pages`);
|
|
74
|
+
},
|
|
75
|
+
|
|
76
|
+
/** Appelle un outil : { content, structuredContent?, isError? }. `timeoutMs` et `signal` par appel. */
|
|
77
|
+
async callTool({ name, arguments: args = {} }, requestOptions = {}) {
|
|
78
|
+
if (typeof name !== 'string' || !name) throw new TypeError('callTool needs a tool name');
|
|
79
|
+
if (!isPlainObject(args)) throw new TypeError('callTool arguments must be an object');
|
|
80
|
+
const result = await session.request('tools/call', { name, arguments: args }, { timeoutMs, ...requestOptions });
|
|
81
|
+
if (!isPlainObject(result)) throw new McpError(ErrorCode.InvalidRequest, 'Invalid tools/call result');
|
|
82
|
+
return { ...result, content: Array.isArray(result.content) ? result.content : [] };
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
async ping(requestOptions = {}) {
|
|
86
|
+
return session.request('ping', undefined, { timeoutMs, ...requestOptions });
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
/** Une autre méthode JSON-RPC (resources/list, prompts/get…), sans vérification du résultat. */
|
|
90
|
+
async request(method, params, requestOptions = {}) {
|
|
91
|
+
return session.request(method, params, { timeoutMs, ...requestOptions });
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
async close() {
|
|
95
|
+
const current = session;
|
|
96
|
+
if (!current) return;
|
|
97
|
+
await current.close().catch(() => {});
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
getServerVersion: () => serverInfo,
|
|
101
|
+
getServerCapabilities: () => serverCapabilities,
|
|
102
|
+
getInstructions: () => instructions,
|
|
103
|
+
get protocolVersion() {
|
|
104
|
+
return protocolVersion;
|
|
105
|
+
},
|
|
106
|
+
onerror: null,
|
|
107
|
+
onclose: null,
|
|
108
|
+
};
|
|
109
|
+
return client;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
module.exports = { createMcpClient };
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
export const LATEST_PROTOCOL_VERSION: '2025-11-25';
|
|
2
|
+
export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION: '2025-03-26';
|
|
3
|
+
export const SUPPORTED_PROTOCOL_VERSIONS: string[];
|
|
4
|
+
export const ErrorCode: { readonly ConnectionClosed: -32000; readonly RequestTimeout: -32001; readonly ParseError: -32700; readonly InvalidRequest: -32600; readonly MethodNotFound: -32601; readonly InvalidParams: -32602; readonly InternalError: -32603 };
|
|
5
|
+
|
|
6
|
+
export class McpError extends Error {
|
|
7
|
+
constructor(code: number, message: string, data?: unknown);
|
|
8
|
+
code: number;
|
|
9
|
+
/** The message without the "MCP error <code>: " prefix. */
|
|
10
|
+
rawMessage: string;
|
|
11
|
+
data?: unknown;
|
|
12
|
+
/** Set when an HTTP transport received a non-2xx status. */
|
|
13
|
+
status?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type JsonRpcId = string | number;
|
|
17
|
+
export interface JsonRpcRequest { jsonrpc: '2.0'; id: JsonRpcId; method: string; params?: Record<string, any> }
|
|
18
|
+
export interface JsonRpcNotification { jsonrpc: '2.0'; method: string; params?: Record<string, any> }
|
|
19
|
+
export type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | { jsonrpc: '2.0'; id: JsonRpcId; result: Record<string, any> } | { jsonrpc: '2.0'; id: JsonRpcId; error: { code: number; message: string; data?: unknown } };
|
|
20
|
+
export function messageKind(message: unknown): 'request' | 'notification' | 'response' | 'error' | null;
|
|
21
|
+
|
|
22
|
+
/** Shaped like the official SDK's transports: an SDK transport plugs in as is. */
|
|
23
|
+
export interface Transport {
|
|
24
|
+
start(): Promise<void>;
|
|
25
|
+
send(message: JsonRpcMessage): Promise<void>;
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
onmessage?: ((message: any) => void) | null;
|
|
28
|
+
onclose?: (() => void) | null;
|
|
29
|
+
onerror?: ((error: Error) => void) | null;
|
|
30
|
+
sessionId?: string;
|
|
31
|
+
setProtocolVersion?(version: string): void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface RequestExtra {
|
|
35
|
+
signal: AbortSignal;
|
|
36
|
+
requestId: JsonRpcId;
|
|
37
|
+
sessionId?: string;
|
|
38
|
+
sendNotification(notification: { method: string; params?: Record<string, any> }): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
export interface RequestOptions { timeoutMs?: number; signal?: AbortSignal }
|
|
41
|
+
export function createSession(options: { onRequest: (request: JsonRpcRequest, extra: RequestExtra) => Promise<Record<string, any>>; onNotification?: (notification: JsonRpcNotification) => void; onError?: (error: Error) => void; onClose?: () => void }): {
|
|
42
|
+
connect(transport: Transport): Promise<void>;
|
|
43
|
+
request(method: string, params?: Record<string, any>, options?: RequestOptions): Promise<any>;
|
|
44
|
+
notify(method: string, params?: Record<string, any>): Promise<void>;
|
|
45
|
+
close(): Promise<void>;
|
|
46
|
+
readonly transport: Transport | null;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export interface ToolDefinition {
|
|
50
|
+
name: string;
|
|
51
|
+
description?: string;
|
|
52
|
+
title?: string;
|
|
53
|
+
inputSchema?: Record<string, any>;
|
|
54
|
+
outputSchema?: Record<string, any>;
|
|
55
|
+
annotations?: { title?: string; readOnlyHint?: boolean; destructiveHint?: boolean; idempotentHint?: boolean; openWorldHint?: boolean };
|
|
56
|
+
[key: string]: unknown;
|
|
57
|
+
}
|
|
58
|
+
export interface ContentPart { type: string; text?: string; data?: string; mimeType?: string; [key: string]: unknown }
|
|
59
|
+
export interface CallToolResult { content: ContentPart[]; structuredContent?: Record<string, any>; isError?: boolean; [key: string]: unknown }
|
|
60
|
+
|
|
61
|
+
export interface McpServer {
|
|
62
|
+
setRequestHandler(method: string, handler: (request: JsonRpcRequest, extra: RequestExtra) => Promise<Record<string, any>> | Record<string, any>): McpServer;
|
|
63
|
+
/** A tool: its handler returns an MCP result or a text. */
|
|
64
|
+
tool(definition: ToolDefinition, handler: (args: Record<string, any>, extra: RequestExtra) => Promise<CallToolResult | string> | CallToolResult | string): McpServer;
|
|
65
|
+
connect(transport: Transport): Promise<void>;
|
|
66
|
+
close(): Promise<void>;
|
|
67
|
+
getClientVersion(): { name: string; version: string } | null;
|
|
68
|
+
getClientCapabilities(): Record<string, any> | null;
|
|
69
|
+
readonly protocolVersion: string | null;
|
|
70
|
+
oninitialized: (() => void) | null;
|
|
71
|
+
onerror: ((error: Error) => void) | null;
|
|
72
|
+
onclose: (() => void) | null;
|
|
73
|
+
}
|
|
74
|
+
export function createMcpServer(info: { name: string; version: string; title?: string }, options?: { capabilities?: Record<string, any>; instructions?: string }): McpServer;
|
|
75
|
+
export function checkArguments(schema: Record<string, any> | undefined, args: unknown): string | null;
|
|
76
|
+
|
|
77
|
+
export interface McpClient {
|
|
78
|
+
connect(transport: Transport, options?: { timeoutMs?: number }): Promise<void>;
|
|
79
|
+
listTools(params?: { cursor?: string }, options?: RequestOptions): Promise<{ tools: ToolDefinition[]; nextCursor?: string }>;
|
|
80
|
+
listAllTools(options?: RequestOptions & { maxPages?: number }): Promise<ToolDefinition[]>;
|
|
81
|
+
callTool(params: { name: string; arguments?: Record<string, any> }, options?: RequestOptions): Promise<CallToolResult>;
|
|
82
|
+
ping(options?: RequestOptions): Promise<Record<string, never>>;
|
|
83
|
+
request(method: string, params?: Record<string, any>, options?: RequestOptions): Promise<any>;
|
|
84
|
+
close(): Promise<void>;
|
|
85
|
+
getServerVersion(): { name: string; version: string; [key: string]: unknown } | null;
|
|
86
|
+
getServerCapabilities(): Record<string, any> | null;
|
|
87
|
+
getInstructions(): string | null;
|
|
88
|
+
readonly protocolVersion: string | null;
|
|
89
|
+
onerror: ((error: Error) => void) | null;
|
|
90
|
+
onclose: (() => void) | null;
|
|
91
|
+
}
|
|
92
|
+
export function createMcpClient(info?: { name: string; version: string }, options?: { capabilities?: Record<string, any>; timeoutMs?: number }): McpClient;
|
|
93
|
+
|
|
94
|
+
export function createInMemoryTransportPair(): [Transport, Transport];
|
|
95
|
+
export function createStdioServerTransport(options?: { stdin?: NodeJS.ReadableStream; stdout?: NodeJS.WritableStream; maxMessageBytes?: number }): Transport;
|
|
96
|
+
export function createStreamableHttpClientTransport(url: string | URL, options?: { headers?: Record<string, string>; fetch?: typeof fetch; maxMessageBytes?: number; maxStreamBytes?: number }): Transport & { readonly sessionId: string | undefined };
|
|
97
|
+
export interface StreamableHttpHandler {
|
|
98
|
+
(req: import('node:http').IncomingMessage & { body?: unknown }, res: import('node:http').ServerResponse): Promise<void>;
|
|
99
|
+
closeAll(): Promise<void>;
|
|
100
|
+
readonly sessionCount: number;
|
|
101
|
+
}
|
|
102
|
+
export function createStreamableHttpHandler(options: { createServer: () => McpServer; allowedOrigins?: string[]; maxBodyBytes?: number; maxSessions?: number; sessionIdleMs?: number; requestTimeoutMs?: number }): StreamableHttpHandler;
|
|
103
|
+
export function readServerSentEvents(body: ReadableStream<Uint8Array>, options?: { maxEventBytes?: number; maxStreamBytes?: number }): AsyncGenerator<{ event: string; data: string; id?: string }>;
|
package/src/index.js
ADDED
package/src/jsonrpc.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/* global AbortController */
|
|
2
|
+
/*
|
|
3
|
+
* Le cœur JSON-RPC 2.0 de MCP : vérifier un message, relier chaque réponse à sa requête, abandonner une requête trop
|
|
4
|
+
* longue (avec notifications/cancelled, comme le SDK), annuler un traitement quand l'autre côté le demande.
|
|
5
|
+
*
|
|
6
|
+
* Un transport a la forme de ceux du SDK officiel : start(), send(message), close(), et les rappels onmessage,
|
|
7
|
+
* onclose, onerror posés par la session. Un transport du SDK se branche donc tel quel.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const LATEST_PROTOCOL_VERSION = '2025-11-25';
|
|
11
|
+
const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];
|
|
12
|
+
const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';
|
|
13
|
+
|
|
14
|
+
const ErrorCode = Object.freeze({
|
|
15
|
+
ConnectionClosed: -32000,
|
|
16
|
+
RequestTimeout: -32001,
|
|
17
|
+
ParseError: -32700,
|
|
18
|
+
InvalidRequest: -32600,
|
|
19
|
+
MethodNotFound: -32601,
|
|
20
|
+
InvalidParams: -32602,
|
|
21
|
+
InternalError: -32603,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
class McpError extends Error {
|
|
25
|
+
constructor(code, message, data) {
|
|
26
|
+
super(`MCP error ${code}: ${message}`);
|
|
27
|
+
this.name = 'McpError';
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.rawMessage = message;
|
|
30
|
+
if (data !== undefined) this.data = data;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
35
|
+
const isId = (id) => (typeof id === 'string' && id.length <= 256) || (Number.isSafeInteger(id));
|
|
36
|
+
|
|
37
|
+
/** La sorte d'un message JSON-RPC 2.0, ou null s'il n'en est pas un. */
|
|
38
|
+
function messageKind(message) {
|
|
39
|
+
if (!isPlainObject(message) || message.jsonrpc !== '2.0') return null;
|
|
40
|
+
const hasMethod = typeof message.method === 'string' && message.method.length > 0 && message.method.length <= 256;
|
|
41
|
+
if (message.params !== undefined && !isPlainObject(message.params)) return null;
|
|
42
|
+
if (hasMethod && 'id' in message) return isId(message.id) ? 'request' : null;
|
|
43
|
+
if (hasMethod) return 'notification';
|
|
44
|
+
if (!('id' in message) || !isId(message.id)) return null;
|
|
45
|
+
if ('result' in message && !('error' in message)) return isPlainObject(message.result) ? 'response' : null;
|
|
46
|
+
if ('error' in message && !('result' in message)) return isPlainObject(message.error) && Number.isInteger(message.error.code) && typeof message.error.message === 'string' ? 'error' : null;
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Une session JSON-RPC sur un transport.
|
|
52
|
+
* @param {object} options
|
|
53
|
+
* @param {(request, extra) => Promise<object>} options.onRequest rend le résultat, ou lève (McpError pour un code)
|
|
54
|
+
* @param {(notification) => void} [options.onNotification]
|
|
55
|
+
* @param {(error) => void} [options.onError]
|
|
56
|
+
* @param {() => void} [options.onClose]
|
|
57
|
+
*/
|
|
58
|
+
function createSession({ onRequest, onNotification = () => {}, onError = () => {}, onClose = () => {} }) {
|
|
59
|
+
let transport = null;
|
|
60
|
+
let nextId = 0;
|
|
61
|
+
let closed = false;
|
|
62
|
+
const pending = new Map();
|
|
63
|
+
const running = new Map();
|
|
64
|
+
|
|
65
|
+
const fail = (error) => {
|
|
66
|
+
try {
|
|
67
|
+
onError(error);
|
|
68
|
+
} catch {
|
|
69
|
+
// un rappel d'erreur qui lève ne doit pas arrêter la session
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
async function send(message) {
|
|
74
|
+
if (!transport || closed) throw new McpError(ErrorCode.ConnectionClosed, 'Connection closed');
|
|
75
|
+
await transport.send(message);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function settle(id, fn) {
|
|
79
|
+
const entry = pending.get(id);
|
|
80
|
+
if (!entry) return;
|
|
81
|
+
pending.delete(id);
|
|
82
|
+
clearTimeout(entry.timer);
|
|
83
|
+
entry.signal?.removeEventListener('abort', entry.onAbort);
|
|
84
|
+
fn(entry);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function handleRequest(message) {
|
|
88
|
+
const controller = new AbortController();
|
|
89
|
+
running.set(message.id, controller);
|
|
90
|
+
let response;
|
|
91
|
+
try {
|
|
92
|
+
const result = await onRequest(message, {
|
|
93
|
+
signal: controller.signal,
|
|
94
|
+
requestId: message.id,
|
|
95
|
+
sessionId: transport?.sessionId,
|
|
96
|
+
sendNotification: (notification) => (controller.signal.aborted ? Promise.resolve() : send({ jsonrpc: '2.0', ...notification })),
|
|
97
|
+
});
|
|
98
|
+
response = { jsonrpc: '2.0', id: message.id, result: isPlainObject(result) ? result : {} };
|
|
99
|
+
} catch (error) {
|
|
100
|
+
const known = error instanceof McpError;
|
|
101
|
+
response = { jsonrpc: '2.0', id: message.id, error: { code: known ? error.code : ErrorCode.InternalError, message: known ? error.rawMessage : 'Internal error', ...(known && error.data !== undefined ? { data: error.data } : {}) } };
|
|
102
|
+
} finally {
|
|
103
|
+
running.delete(message.id);
|
|
104
|
+
}
|
|
105
|
+
// Une requête annulée ne reçoit pas de réponse (spécification MCP, « Cancellation »).
|
|
106
|
+
if (controller.signal.aborted) return;
|
|
107
|
+
await send(response).catch(fail);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function receive(message) {
|
|
111
|
+
const kind = messageKind(message);
|
|
112
|
+
if (kind === 'request') {
|
|
113
|
+
handleRequest(message).catch(fail);
|
|
114
|
+
} else if (kind === 'notification') {
|
|
115
|
+
if (message.method === 'notifications/cancelled') {
|
|
116
|
+
const id = message.params?.requestId;
|
|
117
|
+
running.get(id)?.abort(message.params?.reason);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
onNotification(message);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
fail(error);
|
|
124
|
+
}
|
|
125
|
+
} else if (kind === 'response') {
|
|
126
|
+
settle(message.id, (entry) => entry.resolve(message.result));
|
|
127
|
+
} else if (kind === 'error') {
|
|
128
|
+
settle(message.id, (entry) => entry.reject(new McpError(message.error.code, String(message.error.message).slice(0, 1000), message.error.data)));
|
|
129
|
+
} else {
|
|
130
|
+
fail(new McpError(ErrorCode.InvalidRequest, 'Invalid JSON-RPC message'));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function shutdown() {
|
|
135
|
+
if (closed) return;
|
|
136
|
+
closed = true;
|
|
137
|
+
for (const id of [...pending.keys()]) settle(id, (entry) => entry.reject(new McpError(ErrorCode.ConnectionClosed, 'Connection closed')));
|
|
138
|
+
for (const controller of running.values()) controller.abort();
|
|
139
|
+
running.clear();
|
|
140
|
+
try {
|
|
141
|
+
onClose();
|
|
142
|
+
} catch (error) {
|
|
143
|
+
fail(error);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
async connect(t) {
|
|
149
|
+
if (transport) throw new Error('already connected');
|
|
150
|
+
transport = t;
|
|
151
|
+
t.onmessage = (message) => receive(message);
|
|
152
|
+
t.onerror = (error) => fail(error);
|
|
153
|
+
t.onclose = () => shutdown();
|
|
154
|
+
await t.start();
|
|
155
|
+
},
|
|
156
|
+
|
|
157
|
+
/** Envoie une requête et attend sa réponse (abandon après timeoutMs, ou sur signal, avec notifications/cancelled). */
|
|
158
|
+
request(method, params, { timeoutMs = 60_000, signal } = {}) {
|
|
159
|
+
if (closed || !transport) return Promise.reject(new McpError(ErrorCode.ConnectionClosed, 'Connection closed'));
|
|
160
|
+
if (signal?.aborted) return Promise.reject(signal.reason instanceof Error ? signal.reason : new McpError(ErrorCode.RequestTimeout, 'Request aborted'));
|
|
161
|
+
const id = nextId++;
|
|
162
|
+
return new Promise((resolve, reject) => {
|
|
163
|
+
const cancel = (reason, error) => {
|
|
164
|
+
settle(id, () => reject(error));
|
|
165
|
+
send({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: id, reason } }).catch(() => {});
|
|
166
|
+
};
|
|
167
|
+
const entry = { resolve, reject, signal };
|
|
168
|
+
entry.timer = setTimeout(() => {
|
|
169
|
+
const error = new McpError(ErrorCode.RequestTimeout, 'Request timed out', { timeout: timeoutMs });
|
|
170
|
+
cancel(String(error), error);
|
|
171
|
+
}, timeoutMs);
|
|
172
|
+
entry.timer.unref?.();
|
|
173
|
+
if (signal) {
|
|
174
|
+
entry.onAbort = () => cancel(String(signal.reason?.message || signal.reason || 'aborted'), signal.reason instanceof Error ? signal.reason : new McpError(ErrorCode.RequestTimeout, 'Request aborted'));
|
|
175
|
+
signal.addEventListener('abort', entry.onAbort, { once: true });
|
|
176
|
+
}
|
|
177
|
+
pending.set(id, entry);
|
|
178
|
+
send({ jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }).catch((error) => settle(id, () => reject(error)));
|
|
179
|
+
});
|
|
180
|
+
},
|
|
181
|
+
|
|
182
|
+
notify(method, params) {
|
|
183
|
+
return send({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) });
|
|
184
|
+
},
|
|
185
|
+
|
|
186
|
+
async close() {
|
|
187
|
+
const t = transport;
|
|
188
|
+
shutdown();
|
|
189
|
+
if (t) await t.close();
|
|
190
|
+
},
|
|
191
|
+
|
|
192
|
+
get transport() {
|
|
193
|
+
return transport;
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
module.exports = { createSession, messageKind, McpError, ErrorCode, LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION };
|
package/src/server.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
const { createSession, McpError, ErrorCode, LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS } = require('./jsonrpc');
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Un serveur MCP : la poignée de main (initialize), ping, et les méthodes données par setRequestHandler — ou des outils
|
|
5
|
+
* déclarés avec tool(), qui servent tools/list et tools/call tout seuls. Il remplace Server et McpServer du SDK pour
|
|
6
|
+
* ces usages.
|
|
7
|
+
*
|
|
8
|
+
* Différences voulues avec le SDK :
|
|
9
|
+
* - une exception levée par un traitement revient en « Internal error », sans son message (qui peut contenir un
|
|
10
|
+
* chemin, une requête SQL, une clé) ; une McpError garde son code et son message ;
|
|
11
|
+
* - avec tool(), une exception de l'outil revient en résultat isError: true avec un message générique (McpServer
|
|
12
|
+
* renvoyait le message de l'exception) ; les arguments sont vérifiés contre le schéma de l'outil (objet,
|
|
13
|
+
* required, type et enum des propriétés) avant l'appel ;
|
|
14
|
+
* - initialize ou tools/call sans les paramètres requis répond -32602 avec un message clair (le SDK répondait
|
|
15
|
+
* -32603 avec le vidage de son schéma) ; un curseur inconnu est refusé (-32602), comme le demande la
|
|
16
|
+
* spécification ; capabilities.tools.listChanged vaut false (la liste ne change pas après la connexion).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
20
|
+
const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
21
|
+
const PAGE = 100;
|
|
22
|
+
|
|
23
|
+
/** Une vérification simple d'arguments contre un schéma JSON d'outil (objet, required, type des propriétés). */
|
|
24
|
+
function checkArguments(schema, args) {
|
|
25
|
+
if (!isPlainObject(args)) return 'arguments must be an object';
|
|
26
|
+
if (!isPlainObject(schema)) return null;
|
|
27
|
+
for (const name of Array.isArray(schema.required) ? schema.required : []) {
|
|
28
|
+
if (!Object.hasOwn(args, name)) return `missing required argument "${name}"`;
|
|
29
|
+
}
|
|
30
|
+
const properties = isPlainObject(schema.properties) ? schema.properties : {};
|
|
31
|
+
for (const [name, value] of Object.entries(args)) {
|
|
32
|
+
const property = Object.hasOwn(properties, name) ? properties[name] : null;
|
|
33
|
+
if (!property) {
|
|
34
|
+
if (schema.additionalProperties === false) return `unknown argument "${name}"`;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const types = Array.isArray(property.type) ? property.type : property.type ? [property.type] : [];
|
|
38
|
+
if (!types.length) continue;
|
|
39
|
+
const actual = value === null ? 'null' : Array.isArray(value) ? 'array' : Number.isInteger(value) ? 'integer' : typeof value;
|
|
40
|
+
const ok = types.some((t) => t === actual || (t === 'number' && actual === 'integer'));
|
|
41
|
+
if (!ok) return `argument "${name}" must be ${types.join(' or ')}`;
|
|
42
|
+
if (Array.isArray(property.enum) && !property.enum.some((e) => e === value)) return `argument "${name}" must be one of ${property.enum.map((e) => JSON.stringify(e)).join(', ')}`;
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {object} info { name, version, title? }
|
|
49
|
+
* @param {object} [options] { capabilities, instructions }
|
|
50
|
+
*/
|
|
51
|
+
function createMcpServer(info = {}, options = {}) {
|
|
52
|
+
if (typeof info.name !== 'string' || !info.name || typeof info.version !== 'string' || !info.version) throw new TypeError('createMcpServer needs { name, version }');
|
|
53
|
+
const handlers = new Map();
|
|
54
|
+
const tools = new Map();
|
|
55
|
+
const capabilities = { ...(options.capabilities || {}) };
|
|
56
|
+
let session = null;
|
|
57
|
+
let clientInfo = null;
|
|
58
|
+
let clientCapabilities = null;
|
|
59
|
+
let protocolVersion = null;
|
|
60
|
+
let oninitialized = null;
|
|
61
|
+
|
|
62
|
+
const server = {
|
|
63
|
+
/** Une méthode JSON-RPC : handler(request, extra) rend le résultat (objet) ou lève. */
|
|
64
|
+
setRequestHandler(method, handler) {
|
|
65
|
+
if (typeof method !== 'string' || typeof handler !== 'function') throw new TypeError('setRequestHandler(method, handler)');
|
|
66
|
+
if (method === 'initialize' || method === 'ping') throw new Error(`${method} is handled by the server`);
|
|
67
|
+
if (method.startsWith('tools/') && !capabilities.tools) throw new Error('Server does not support tools (declare capabilities.tools)');
|
|
68
|
+
handlers.set(method, handler);
|
|
69
|
+
return server;
|
|
70
|
+
},
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Un outil : { name, description, inputSchema, annotations?, title?, outputSchema? }, et handler(args, extra) qui
|
|
74
|
+
* rend un résultat MCP ({ content: [...] }) ou un texte.
|
|
75
|
+
*/
|
|
76
|
+
tool(definition, handler) {
|
|
77
|
+
if (!isPlainObject(definition) || !TOOL_NAME.test(definition.name || '')) throw new TypeError('tool needs a name of letters, digits, "_", "-" or "." (128 at most)');
|
|
78
|
+
if (typeof handler !== 'function') throw new TypeError('tool needs a handler');
|
|
79
|
+
if (tools.has(definition.name)) throw new Error(`tool ${definition.name} is already registered`);
|
|
80
|
+
const inputSchema = isPlainObject(definition.inputSchema) ? definition.inputSchema : { type: 'object', properties: {} };
|
|
81
|
+
tools.set(definition.name, { definition: { ...definition, inputSchema }, handler });
|
|
82
|
+
if (!capabilities.tools) capabilities.tools = { listChanged: false };
|
|
83
|
+
if (!handlers.has('tools/list')) {
|
|
84
|
+
handlers.set('tools/list', async (request) => {
|
|
85
|
+
const all = [...tools.values()].map((t) => t.definition);
|
|
86
|
+
const start = request.params?.cursor === undefined ? 0 : Number.parseInt(String(request.params.cursor), 10);
|
|
87
|
+
if (!Number.isSafeInteger(start) || start < 0 || start > all.length) throw new McpError(ErrorCode.InvalidParams, 'Invalid cursor');
|
|
88
|
+
const page = all.slice(start, start + PAGE);
|
|
89
|
+
return { tools: page, ...(start + PAGE < all.length ? { nextCursor: String(start + PAGE) } : {}) };
|
|
90
|
+
});
|
|
91
|
+
handlers.set('tools/call', async (request, extra) => {
|
|
92
|
+
const name = request.params?.name;
|
|
93
|
+
if (typeof name !== 'string') throw new McpError(ErrorCode.InvalidParams, 'Invalid params: name is required');
|
|
94
|
+
// Comme McpServer du SDK : un outil inconnu ou des arguments invalides reviennent en résultat isError, pour que
|
|
95
|
+
// le modèle se corrige (spécification MCP 2025-11-25, erreurs d'exécution d'outil).
|
|
96
|
+
const toolError = (text) => ({ content: [{ type: 'text', text }], isError: true });
|
|
97
|
+
const entry = tools.get(name);
|
|
98
|
+
if (!entry) return toolError(`MCP error -32602: Tool ${String(name).slice(0, 128)} not found`);
|
|
99
|
+
const given = request.params.arguments === undefined ? {} : request.params.arguments;
|
|
100
|
+
const problem = checkArguments({ ...entry.definition.inputSchema, additionalProperties: true }, given);
|
|
101
|
+
if (problem) return toolError(`MCP error -32602: Input validation error: Invalid arguments for tool ${name}: ${problem}`);
|
|
102
|
+
// Un argument hors du schéma (additionalProperties: false) est retiré avant l'appel, comme le fait le SDK.
|
|
103
|
+
const schema = entry.definition.inputSchema;
|
|
104
|
+
const args = schema.additionalProperties === false && isPlainObject(schema.properties) ? Object.fromEntries(Object.entries(given).filter(([k]) => Object.hasOwn(schema.properties, k))) : given;
|
|
105
|
+
try {
|
|
106
|
+
const result = await entry.handler(args, extra);
|
|
107
|
+
if (typeof result === 'string') return { content: [{ type: 'text', text: result }] };
|
|
108
|
+
return isPlainObject(result) ? result : { content: [] };
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (extra.signal.aborted) throw error;
|
|
111
|
+
if (error instanceof McpError) throw error;
|
|
112
|
+
return { isError: true, content: [{ type: 'text', text: `Tool ${name} failed` }] };
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return server;
|
|
117
|
+
},
|
|
118
|
+
|
|
119
|
+
async connect(transport) {
|
|
120
|
+
if (session) throw new Error('already connected');
|
|
121
|
+
session = createSession({
|
|
122
|
+
onRequest: async (request, extra) => {
|
|
123
|
+
if (request.method === 'initialize') {
|
|
124
|
+
const params = request.params;
|
|
125
|
+
if (!isPlainObject(params) || typeof params.protocolVersion !== 'string') throw new McpError(ErrorCode.InvalidParams, 'Invalid params: initialize needs params.protocolVersion');
|
|
126
|
+
const requested = params.protocolVersion;
|
|
127
|
+
protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : LATEST_PROTOCOL_VERSION;
|
|
128
|
+
clientInfo = isPlainObject(params.clientInfo) ? params.clientInfo : null;
|
|
129
|
+
clientCapabilities = isPlainObject(params.capabilities) ? params.capabilities : null;
|
|
130
|
+
return { protocolVersion, capabilities, serverInfo: { ...info }, ...(options.instructions ? { instructions: options.instructions } : {}) };
|
|
131
|
+
}
|
|
132
|
+
if (request.method === 'ping') return {};
|
|
133
|
+
const handler = handlers.get(request.method);
|
|
134
|
+
if (!handler) throw new McpError(ErrorCode.MethodNotFound, 'Method not found');
|
|
135
|
+
return handler(request, extra);
|
|
136
|
+
},
|
|
137
|
+
onNotification: (notification) => {
|
|
138
|
+
if (notification.method === 'notifications/initialized') oninitialized?.();
|
|
139
|
+
},
|
|
140
|
+
onError: (error) => server.onerror?.(error),
|
|
141
|
+
onClose: () => server.onclose?.(),
|
|
142
|
+
});
|
|
143
|
+
await session.connect(transport);
|
|
144
|
+
},
|
|
145
|
+
|
|
146
|
+
async close() {
|
|
147
|
+
if (session) await session.close();
|
|
148
|
+
},
|
|
149
|
+
|
|
150
|
+
getClientVersion: () => clientInfo,
|
|
151
|
+
getClientCapabilities: () => clientCapabilities,
|
|
152
|
+
get protocolVersion() {
|
|
153
|
+
return protocolVersion;
|
|
154
|
+
},
|
|
155
|
+
set oninitialized(fn) {
|
|
156
|
+
oninitialized = fn;
|
|
157
|
+
},
|
|
158
|
+
onerror: null,
|
|
159
|
+
onclose: null,
|
|
160
|
+
};
|
|
161
|
+
return server;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
module.exports = { createMcpServer, checkArguments };
|
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
/* global AbortController, TextDecoder, queueMicrotask */
|
|
2
|
+
const crypto = require('node:crypto');
|
|
3
|
+
const { messageKind, McpError, ErrorCode, SUPPORTED_PROTOCOL_VERSIONS } = require('./jsonrpc');
|
|
4
|
+
|
|
5
|
+
/*
|
|
6
|
+
* Les transports MCP, à la forme de ceux du SDK (start, send, close ; onmessage, onclose, onerror) :
|
|
7
|
+
* - createInMemoryTransportPair : deux bouts reliés, pour les essais ;
|
|
8
|
+
* - createStdioServerTransport : un message JSON par ligne sur stdin et stdout (un éditeur lance le serveur) ;
|
|
9
|
+
* - createStreamableHttpClientTransport : le client « Streamable HTTP » (POST, réponse JSON ou flux SSE, session) ;
|
|
10
|
+
* - createStreamableHttpHandler : le serveur « Streamable HTTP », un gestionnaire (req, res) pour node:http ou
|
|
11
|
+
* Express, une session par client.
|
|
12
|
+
*
|
|
13
|
+
* Protections : l'adresse d'un serveur distant doit être en https:// (http:// seulement vers la machine), sans
|
|
14
|
+
* identifiants ; aucune redirection suivie ; un message de 4 Mio au plus, un flux de 16 Mio au plus ; côté serveur,
|
|
15
|
+
* l'en-tête Origin est vérifié (une page web ne peut pas parler au serveur sans être permise : attaque de « DNS
|
|
16
|
+
* rebinding »), le corps est plafonné, les sessions sont limitées en nombre et en durée d'inactivité.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const MAX_MESSAGE = 4 * 1024 * 1024;
|
|
20
|
+
const MAX_STREAM = 16 * 1024 * 1024;
|
|
21
|
+
const LOOPBACK = new Set(['127.0.0.1', '[::1]', 'localhost']);
|
|
22
|
+
const SESSION_ID = /^[\x21-\x7e]{1,256}$/;
|
|
23
|
+
|
|
24
|
+
const parseJson = (text) => {
|
|
25
|
+
try {
|
|
26
|
+
return { ok: true, value: JSON.parse(text) };
|
|
27
|
+
} catch {
|
|
28
|
+
return { ok: false };
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** Deux bouts reliés : ce qu'envoie l'un, l'autre le reçoit (copié, comme sur un vrai fil). */
|
|
33
|
+
function createInMemoryTransportPair() {
|
|
34
|
+
const make = () => ({ other: null, closed: false, onmessage: null, onclose: null, onerror: null });
|
|
35
|
+
const a = make();
|
|
36
|
+
const b = make();
|
|
37
|
+
a.other = b;
|
|
38
|
+
b.other = a;
|
|
39
|
+
for (const side of [a, b]) {
|
|
40
|
+
side.start = async () => {};
|
|
41
|
+
side.send = async (message) => {
|
|
42
|
+
if (side.closed) throw new McpError(ErrorCode.ConnectionClosed, 'Connection closed');
|
|
43
|
+
const copy = JSON.parse(JSON.stringify(message));
|
|
44
|
+
queueMicrotask(() => side.other.onmessage?.(copy));
|
|
45
|
+
};
|
|
46
|
+
side.close = async () => {
|
|
47
|
+
for (const s of [side, side.other]) {
|
|
48
|
+
if (s.closed) continue;
|
|
49
|
+
s.closed = true;
|
|
50
|
+
s.onclose?.();
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
return [a, b];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Le serveur en stdio : une ligne JSON par message. */
|
|
58
|
+
function createStdioServerTransport({ stdin = process.stdin, stdout = process.stdout, maxMessageBytes = MAX_MESSAGE } = {}) {
|
|
59
|
+
let buffer = '';
|
|
60
|
+
let started = false;
|
|
61
|
+
const transport = {
|
|
62
|
+
onmessage: null,
|
|
63
|
+
onclose: null,
|
|
64
|
+
onerror: null,
|
|
65
|
+
async start() {
|
|
66
|
+
if (started) throw new Error('already started');
|
|
67
|
+
started = true;
|
|
68
|
+
stdin.setEncoding?.('utf8');
|
|
69
|
+
stdin.on('data', onData);
|
|
70
|
+
stdin.on('error', onError);
|
|
71
|
+
stdin.on('end', onEnd);
|
|
72
|
+
},
|
|
73
|
+
async send(message) {
|
|
74
|
+
const line = `${JSON.stringify(message)}\n`;
|
|
75
|
+
if (!stdout.write(line)) await new Promise((resolve) => stdout.once('drain', resolve));
|
|
76
|
+
},
|
|
77
|
+
async close() {
|
|
78
|
+
stdin.off('data', onData);
|
|
79
|
+
stdin.off('error', onError);
|
|
80
|
+
stdin.off('end', onEnd);
|
|
81
|
+
stdin.pause?.();
|
|
82
|
+
buffer = '';
|
|
83
|
+
transport.onclose?.();
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
function onData(chunk) {
|
|
87
|
+
buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
|
|
88
|
+
let index;
|
|
89
|
+
while ((index = buffer.indexOf('\n')) >= 0) {
|
|
90
|
+
const line = buffer.slice(0, index).replace(/\r$/, '');
|
|
91
|
+
buffer = buffer.slice(index + 1);
|
|
92
|
+
if (!line.trim()) continue;
|
|
93
|
+
const parsed = parseJson(line);
|
|
94
|
+
if (!parsed.ok) transport.onerror?.(new McpError(ErrorCode.ParseError, 'Parse error'));
|
|
95
|
+
else transport.onmessage?.(parsed.value);
|
|
96
|
+
}
|
|
97
|
+
if (Buffer.byteLength(buffer) > maxMessageBytes) {
|
|
98
|
+
buffer = '';
|
|
99
|
+
transport.onerror?.(new McpError(ErrorCode.InvalidRequest, `message larger than ${maxMessageBytes} bytes`));
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function onError(error) {
|
|
103
|
+
transport.onerror?.(error);
|
|
104
|
+
}
|
|
105
|
+
function onEnd() {
|
|
106
|
+
transport.close().catch(() => {});
|
|
107
|
+
}
|
|
108
|
+
return transport;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Lit un flux SSE (text/event-stream) et rend chaque événement { event, data, id }. */
|
|
112
|
+
async function* readServerSentEvents(body, { maxEventBytes = MAX_MESSAGE, maxStreamBytes = MAX_STREAM } = {}) {
|
|
113
|
+
const decoder = new TextDecoder();
|
|
114
|
+
let buffer = '';
|
|
115
|
+
let total = 0;
|
|
116
|
+
let event = { event: 'message', data: [], id: undefined };
|
|
117
|
+
const reader = body.getReader();
|
|
118
|
+
try {
|
|
119
|
+
for (;;) {
|
|
120
|
+
const { value, done } = await reader.read();
|
|
121
|
+
if (done) break;
|
|
122
|
+
total += value.byteLength;
|
|
123
|
+
if (total > maxStreamBytes) throw new McpError(ErrorCode.InvalidRequest, `stream larger than ${maxStreamBytes} bytes`);
|
|
124
|
+
buffer += decoder.decode(value, { stream: true });
|
|
125
|
+
let index;
|
|
126
|
+
while ((index = buffer.search(/\r\n|\r|\n/)) >= 0) {
|
|
127
|
+
const line = buffer.slice(0, index);
|
|
128
|
+
buffer = buffer.slice(index + (buffer[index] === '\r' && buffer[index + 1] === '\n' ? 2 : 1));
|
|
129
|
+
if (line === '') {
|
|
130
|
+
if (event.data.length) yield { event: event.event, data: event.data.join('\n'), id: event.id };
|
|
131
|
+
event = { event: 'message', data: [], id: undefined };
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (line.startsWith(':')) continue;
|
|
135
|
+
const colon = line.indexOf(':');
|
|
136
|
+
const field = colon < 0 ? line : line.slice(0, colon);
|
|
137
|
+
let content = colon < 0 ? '' : line.slice(colon + 1);
|
|
138
|
+
if (content.startsWith(' ')) content = content.slice(1);
|
|
139
|
+
if (field === 'data') {
|
|
140
|
+
event.data.push(content);
|
|
141
|
+
if (event.data.reduce((n, d) => n + d.length, 0) > maxEventBytes) throw new McpError(ErrorCode.InvalidRequest, `event larger than ${maxEventBytes} bytes`);
|
|
142
|
+
} else if (field === 'event') event.event = content;
|
|
143
|
+
else if (field === 'id' && !content.includes('\0')) event.id = content;
|
|
144
|
+
}
|
|
145
|
+
if (buffer.length > maxEventBytes) throw new McpError(ErrorCode.InvalidRequest, `line larger than ${maxEventBytes} bytes`);
|
|
146
|
+
}
|
|
147
|
+
if (event.data.length) yield { event: event.event, data: event.data.join('\n'), id: event.id };
|
|
148
|
+
} finally {
|
|
149
|
+
reader.cancel().catch(() => {});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function readLimited(response, limit) {
|
|
154
|
+
const reader = response.body?.getReader();
|
|
155
|
+
if (!reader) return '';
|
|
156
|
+
const chunks = [];
|
|
157
|
+
let size = 0;
|
|
158
|
+
try {
|
|
159
|
+
for (;;) {
|
|
160
|
+
const { value, done } = await reader.read();
|
|
161
|
+
if (done) break;
|
|
162
|
+
size += value.byteLength;
|
|
163
|
+
if (size > limit) throw new McpError(ErrorCode.InvalidRequest, `response larger than ${limit} bytes`);
|
|
164
|
+
chunks.push(value);
|
|
165
|
+
}
|
|
166
|
+
} finally {
|
|
167
|
+
reader.cancel().catch(() => {});
|
|
168
|
+
}
|
|
169
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function checkUrl(url) {
|
|
173
|
+
let parsed;
|
|
174
|
+
try {
|
|
175
|
+
parsed = new URL(url);
|
|
176
|
+
} catch {
|
|
177
|
+
throw new TypeError('MCP server url must be a URL');
|
|
178
|
+
}
|
|
179
|
+
if (parsed.username || parsed.password) throw new TypeError('MCP server url must not contain credentials (use headers)');
|
|
180
|
+
if (parsed.protocol === 'http:' && !LOOPBACK.has(parsed.hostname)) throw new TypeError('MCP server url must use https:// (http:// only to this machine)');
|
|
181
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') throw new TypeError('MCP server url must use https://');
|
|
182
|
+
return parsed;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const MANAGED = new Set(['content-type', 'accept', 'mcp-session-id', 'mcp-protocol-version', 'content-length', 'host']);
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Le client « Streamable HTTP ».
|
|
189
|
+
* @param {string|URL} url
|
|
190
|
+
* @param {object} [options] { headers, fetch, maxMessageBytes, maxStreamBytes }
|
|
191
|
+
*/
|
|
192
|
+
function createStreamableHttpClientTransport(url, options = {}) {
|
|
193
|
+
const endpoint = checkUrl(url);
|
|
194
|
+
const fetchFn = options.fetch || globalThis.fetch;
|
|
195
|
+
const extra = {};
|
|
196
|
+
for (const [name, value] of Object.entries(options.headers || {})) {
|
|
197
|
+
if (MANAGED.has(name.toLowerCase())) throw new TypeError(`header ${name} is set by the transport`);
|
|
198
|
+
if (/[\r\n]/.test(String(value))) throw new TypeError(`header ${name} has a line break`);
|
|
199
|
+
extra[name] = String(value);
|
|
200
|
+
}
|
|
201
|
+
const maxMessageBytes = options.maxMessageBytes ?? MAX_MESSAGE;
|
|
202
|
+
const maxStreamBytes = options.maxStreamBytes ?? MAX_STREAM;
|
|
203
|
+
let controller = new AbortController();
|
|
204
|
+
let sessionId;
|
|
205
|
+
let protocolVersion;
|
|
206
|
+
let closed = false;
|
|
207
|
+
|
|
208
|
+
const headers = (more) => ({ ...extra, ...(sessionId ? { 'mcp-session-id': sessionId } : {}), ...(protocolVersion ? { 'mcp-protocol-version': protocolVersion } : {}), ...more });
|
|
209
|
+
const deliver = (value) => {
|
|
210
|
+
for (const message of Array.isArray(value) ? value : [value]) transport.onmessage?.(message);
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const transport = {
|
|
214
|
+
onmessage: null,
|
|
215
|
+
onclose: null,
|
|
216
|
+
onerror: null,
|
|
217
|
+
async start() {},
|
|
218
|
+
setProtocolVersion(version) {
|
|
219
|
+
protocolVersion = version;
|
|
220
|
+
},
|
|
221
|
+
get sessionId() {
|
|
222
|
+
return sessionId;
|
|
223
|
+
},
|
|
224
|
+
async send(message) {
|
|
225
|
+
if (closed) throw new McpError(ErrorCode.ConnectionClosed, 'Connection closed');
|
|
226
|
+
const response = await fetchFn(endpoint, { method: 'POST', headers: headers({ 'content-type': 'application/json', accept: 'application/json, text/event-stream' }), body: JSON.stringify(message), redirect: 'manual', signal: controller.signal });
|
|
227
|
+
const newSession = response.headers.get('mcp-session-id');
|
|
228
|
+
if (newSession) {
|
|
229
|
+
if (!SESSION_ID.test(newSession)) throw new McpError(ErrorCode.InvalidRequest, 'Invalid session id from server');
|
|
230
|
+
sessionId = newSession;
|
|
231
|
+
}
|
|
232
|
+
if (response.status === 202) {
|
|
233
|
+
response.body?.cancel().catch(() => {});
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (!response.ok) {
|
|
237
|
+
const text = await readLimited(response, 64 * 1024).catch(() => '');
|
|
238
|
+
if (response.status === 404 && sessionId) sessionId = undefined;
|
|
239
|
+
const parsed = parseJson(text);
|
|
240
|
+
const detail = parsed.ok && parsed.value?.error?.message ? `: ${String(parsed.value.error.message).slice(0, 200)}` : '';
|
|
241
|
+
const error = new McpError(ErrorCode.ConnectionClosed, `HTTP ${response.status} from MCP server${detail}`);
|
|
242
|
+
error.status = response.status;
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
const type = (response.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
|
|
246
|
+
if (type === 'application/json') {
|
|
247
|
+
const parsed = parseJson(await readLimited(response, maxMessageBytes));
|
|
248
|
+
if (!parsed.ok) throw new McpError(ErrorCode.ParseError, 'Invalid JSON from MCP server');
|
|
249
|
+
deliver(parsed.value);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (type === 'text/event-stream') {
|
|
253
|
+
const expected = messageKind(message) === 'request' ? message.id : undefined;
|
|
254
|
+
// Le flux est lu sans bloquer l'envoi : la réponse arrive par onmessage. Si le flux d'une requête casse ou se
|
|
255
|
+
// termine sans sa réponse, la requête échoue tout de suite (au lieu d'attendre son délai).
|
|
256
|
+
const failRequest = (message2) => {
|
|
257
|
+
if (expected !== undefined && !closed) transport.onmessage?.({ jsonrpc: '2.0', id: expected, error: { code: ErrorCode.ConnectionClosed, message: message2 } });
|
|
258
|
+
};
|
|
259
|
+
(async () => {
|
|
260
|
+
for await (const event of readServerSentEvents(response.body, { maxEventBytes: maxMessageBytes, maxStreamBytes })) {
|
|
261
|
+
if (event.event !== 'message') continue;
|
|
262
|
+
const parsed = parseJson(event.data);
|
|
263
|
+
if (!parsed.ok) {
|
|
264
|
+
transport.onerror?.(new McpError(ErrorCode.ParseError, 'Invalid JSON in event stream'));
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
deliver(parsed.value);
|
|
268
|
+
if (expected !== undefined && (Array.isArray(parsed.value) ? parsed.value : [parsed.value]).some((m) => m && m.id === expected && ('result' in m || 'error' in m))) return;
|
|
269
|
+
}
|
|
270
|
+
failRequest('Event stream ended without a response');
|
|
271
|
+
})().catch((error) => {
|
|
272
|
+
if (closed) return;
|
|
273
|
+
transport.onerror?.(error);
|
|
274
|
+
failRequest(error instanceof McpError ? error.rawMessage : 'Event stream failed');
|
|
275
|
+
});
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
response.body?.cancel().catch(() => {});
|
|
279
|
+
throw new McpError(ErrorCode.InvalidRequest, `Unexpected content type from MCP server: ${type.slice(0, 60)}`);
|
|
280
|
+
},
|
|
281
|
+
async close() {
|
|
282
|
+
if (closed) return;
|
|
283
|
+
closed = true;
|
|
284
|
+
controller.abort();
|
|
285
|
+
// La session est fermée chez le serveur (spécification MCP : DELETE quand le client n'en a plus besoin).
|
|
286
|
+
if (sessionId) {
|
|
287
|
+
const goodbye = new AbortController();
|
|
288
|
+
const timer = setTimeout(() => goodbye.abort(), 5000);
|
|
289
|
+
timer.unref?.();
|
|
290
|
+
await fetchFn(endpoint, { method: 'DELETE', headers: headers({}), redirect: 'manual', signal: goodbye.signal })
|
|
291
|
+
.then((r) => r.body?.cancel())
|
|
292
|
+
.catch(() => {})
|
|
293
|
+
.finally(() => clearTimeout(timer));
|
|
294
|
+
}
|
|
295
|
+
controller = new AbortController();
|
|
296
|
+
transport.onclose?.();
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
return transport;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Le transport d'une session côté serveur HTTP : chaque réponse va à la requête HTTP qui attend son id. */
|
|
303
|
+
function sessionTransport() {
|
|
304
|
+
const waiting = new Map();
|
|
305
|
+
return {
|
|
306
|
+
onmessage: null,
|
|
307
|
+
onclose: null,
|
|
308
|
+
onerror: null,
|
|
309
|
+
sessionId: undefined,
|
|
310
|
+
waiting,
|
|
311
|
+
async start() {},
|
|
312
|
+
async send(message) {
|
|
313
|
+
const resolve = message && message.id !== undefined ? waiting.get(message.id) : undefined;
|
|
314
|
+
if (resolve) {
|
|
315
|
+
waiting.delete(message.id);
|
|
316
|
+
resolve(message);
|
|
317
|
+
}
|
|
318
|
+
// Une notification du serveur hors d'une réponse est ignorée : pas de flux GET ouvert.
|
|
319
|
+
},
|
|
320
|
+
async close() {
|
|
321
|
+
for (const resolve of waiting.values()) resolve(null);
|
|
322
|
+
waiting.clear();
|
|
323
|
+
this.onclose?.();
|
|
324
|
+
},
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function readBody(req, limit) {
|
|
329
|
+
if (req.body !== undefined) return Promise.resolve(typeof req.body === 'string' ? req.body : Buffer.isBuffer(req.body) ? req.body.toString('utf8') : JSON.stringify(req.body));
|
|
330
|
+
return new Promise((resolve, reject) => {
|
|
331
|
+
const chunks = [];
|
|
332
|
+
let size = 0;
|
|
333
|
+
req.on('data', (chunk) => {
|
|
334
|
+
size += chunk.length;
|
|
335
|
+
if (size > limit) {
|
|
336
|
+
// La lecture s'arrête ici ; la connexion est fermée une fois la réponse 413 partie.
|
|
337
|
+
reject(Object.assign(new Error('too large'), { status: 413 }));
|
|
338
|
+
req.pause();
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
chunks.push(chunk);
|
|
342
|
+
});
|
|
343
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
344
|
+
req.on('error', reject);
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Le serveur « Streamable HTTP » : (req, res) pour node:http ou Express. `createServer()` rend un serveur MCP neuf
|
|
350
|
+
* (createMcpServer) pour chaque session.
|
|
351
|
+
* @param {object} options { createServer, allowedOrigins = [], maxBodyBytes = 4 Mio, maxSessions = 1000,
|
|
352
|
+
* sessionIdleMs = 30 min, requestTimeoutMs = 5 min }
|
|
353
|
+
*/
|
|
354
|
+
function createStreamableHttpHandler({ createServer, allowedOrigins = [], maxBodyBytes = MAX_MESSAGE, maxSessions = 1000, sessionIdleMs = 30 * 60_000, requestTimeoutMs = 5 * 60_000 } = {}) {
|
|
355
|
+
if (typeof createServer !== 'function') throw new TypeError('createStreamableHttpHandler needs createServer()');
|
|
356
|
+
const sessions = new Map();
|
|
357
|
+
|
|
358
|
+
const reply = (res, status, body, headers = {}) => {
|
|
359
|
+
if (res.headersSent) return;
|
|
360
|
+
const text = body === undefined ? '' : JSON.stringify(body);
|
|
361
|
+
res.writeHead(status, { ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...headers });
|
|
362
|
+
res.end(text);
|
|
363
|
+
};
|
|
364
|
+
const rpcError = (code, message, id = null) => ({ jsonrpc: '2.0', error: { code, message }, id });
|
|
365
|
+
|
|
366
|
+
// Une session expire après sessionIdleMs sans requête, jamais pendant qu'une requête est en cours.
|
|
367
|
+
function touch(entry) {
|
|
368
|
+
clearTimeout(entry.timer);
|
|
369
|
+
entry.timer = setTimeout(() => {
|
|
370
|
+
if (entry.inflight > 0) touch(entry);
|
|
371
|
+
else closeSession(entry.id);
|
|
372
|
+
}, sessionIdleMs);
|
|
373
|
+
entry.timer.unref?.();
|
|
374
|
+
}
|
|
375
|
+
async function closeSession(id) {
|
|
376
|
+
const entry = sessions.get(id);
|
|
377
|
+
if (!entry) return;
|
|
378
|
+
sessions.delete(id);
|
|
379
|
+
clearTimeout(entry.timer);
|
|
380
|
+
await entry.server.close().catch(() => {});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async function handler(req, res) {
|
|
384
|
+
try {
|
|
385
|
+
const origin = req.headers.origin;
|
|
386
|
+
if (origin !== undefined && !allowedOrigins.includes(origin)) return reply(res, 403, rpcError(ErrorCode.ConnectionClosed, 'Forbidden: origin not allowed'));
|
|
387
|
+
const version = req.headers['mcp-protocol-version'];
|
|
388
|
+
if (version !== undefined && !SUPPORTED_PROTOCOL_VERSIONS.includes(version)) return reply(res, 400, rpcError(ErrorCode.ConnectionClosed, `Bad Request: Unsupported protocol version: ${String(version).slice(0, 40)} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`));
|
|
389
|
+
const sessionHeader = req.headers['mcp-session-id'];
|
|
390
|
+
|
|
391
|
+
if (req.method === 'GET' || req.method === 'DELETE') {
|
|
392
|
+
if (!sessionHeader) return reply(res, 400, rpcError(ErrorCode.ConnectionClosed, 'Bad Request: Mcp-Session-Id header is required'));
|
|
393
|
+
if (!sessions.has(sessionHeader)) return reply(res, 404, rpcError(-32001, 'Session not found'));
|
|
394
|
+
// Pas de flux GET : le serveur n'envoie rien au client hors des réponses à ses requêtes.
|
|
395
|
+
if (req.method === 'GET') return reply(res, 405, rpcError(ErrorCode.ConnectionClosed, 'Method not allowed.'), { allow: 'POST, DELETE' });
|
|
396
|
+
await closeSession(sessionHeader);
|
|
397
|
+
return reply(res, 200);
|
|
398
|
+
}
|
|
399
|
+
if (req.method !== 'POST') return reply(res, 405, rpcError(ErrorCode.ConnectionClosed, 'Method not allowed.'), { allow: 'POST, DELETE' });
|
|
400
|
+
|
|
401
|
+
const accept = String(req.headers.accept || '');
|
|
402
|
+
if (!accept.includes('application/json') || !accept.includes('text/event-stream')) return reply(res, 406, rpcError(ErrorCode.ConnectionClosed, 'Not Acceptable: Client must accept both application/json and text/event-stream'));
|
|
403
|
+
if (!String(req.headers['content-type'] || '').includes('application/json')) return reply(res, 415, rpcError(ErrorCode.ConnectionClosed, 'Unsupported Media Type: Content-Type must be application/json'));
|
|
404
|
+
|
|
405
|
+
let text;
|
|
406
|
+
try {
|
|
407
|
+
text = await readBody(req, maxBodyBytes);
|
|
408
|
+
} catch (error) {
|
|
409
|
+
res.on('finish', () => req.destroy());
|
|
410
|
+
return reply(res, error.status === 413 ? 413 : 400, rpcError(ErrorCode.ParseError, error.status === 413 ? 'Payload too large' : 'Parse error'), { connection: 'close' });
|
|
411
|
+
}
|
|
412
|
+
const parsed = parseJson(text);
|
|
413
|
+
if (!parsed.ok) return reply(res, 400, rpcError(ErrorCode.ParseError, 'Parse error: Invalid JSON-RPC message'));
|
|
414
|
+
const batch = Array.isArray(parsed.value);
|
|
415
|
+
const messages = batch ? parsed.value : [parsed.value];
|
|
416
|
+
if (!messages.length || messages.length > 100 || messages.some((m) => messageKind(m) === null)) return reply(res, 400, rpcError(ErrorCode.ParseError, 'Parse error: Invalid JSON-RPC message'));
|
|
417
|
+
|
|
418
|
+
const initialize = messages.some((m) => m.method === 'initialize' && messageKind(m) === 'request');
|
|
419
|
+
let entry;
|
|
420
|
+
if (initialize) {
|
|
421
|
+
if (messages.length > 1) return reply(res, 400, rpcError(ErrorCode.InvalidRequest, 'Invalid Request: Only one initialization request is allowed'));
|
|
422
|
+
if (sessionHeader && sessions.has(sessionHeader)) return reply(res, 400, rpcError(ErrorCode.InvalidRequest, 'Invalid Request: Server already initialized'));
|
|
423
|
+
if (sessions.size >= maxSessions) return reply(res, 503, rpcError(ErrorCode.ConnectionClosed, 'Too many sessions'));
|
|
424
|
+
const transport = sessionTransport();
|
|
425
|
+
transport.sessionId = crypto.randomUUID();
|
|
426
|
+
const server = createServer();
|
|
427
|
+
await server.connect(transport);
|
|
428
|
+
entry = { id: transport.sessionId, server, transport, inflight: 0 };
|
|
429
|
+
sessions.set(entry.id, entry);
|
|
430
|
+
} else {
|
|
431
|
+
if (!sessionHeader) return reply(res, 400, rpcError(ErrorCode.ConnectionClosed, 'Bad Request: Mcp-Session-Id header is required'));
|
|
432
|
+
entry = sessions.get(sessionHeader);
|
|
433
|
+
if (!entry) return reply(res, 404, rpcError(-32001, 'Session not found'));
|
|
434
|
+
}
|
|
435
|
+
touch(entry);
|
|
436
|
+
|
|
437
|
+
const requests = messages.filter((m) => messageKind(m) === 'request');
|
|
438
|
+
const answers = requests.map((m) => new Promise((resolve) => {
|
|
439
|
+
if (entry.transport.waiting.has(m.id)) {
|
|
440
|
+
resolve(rpcError(ErrorCode.InvalidRequest, 'Duplicate request id', m.id));
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
entry.transport.waiting.set(m.id, resolve);
|
|
444
|
+
}));
|
|
445
|
+
for (const message of messages) entry.transport.onmessage?.(message);
|
|
446
|
+
if (!requests.length) return reply(res, 202);
|
|
447
|
+
|
|
448
|
+
let timer;
|
|
449
|
+
const timeout = new Promise((resolve) => {
|
|
450
|
+
timer = setTimeout(() => resolve('timeout'), requestTimeoutMs);
|
|
451
|
+
timer.unref?.();
|
|
452
|
+
});
|
|
453
|
+
entry.inflight += 1;
|
|
454
|
+
const results = await Promise.race([Promise.all(answers), timeout]);
|
|
455
|
+
entry.inflight -= 1;
|
|
456
|
+
clearTimeout(timer);
|
|
457
|
+
touch(entry);
|
|
458
|
+
if (results === 'timeout') {
|
|
459
|
+
for (const m of requests) entry.transport.waiting.delete(m.id);
|
|
460
|
+
return reply(res, 504, rpcError(ErrorCode.RequestTimeout, 'Request timed out'));
|
|
461
|
+
}
|
|
462
|
+
const body = results.map((r, i) => r || rpcError(ErrorCode.ConnectionClosed, 'Connection closed', requests[i].id));
|
|
463
|
+
return reply(res, 200, batch ? body : body[0], initialize ? { 'mcp-session-id': entry.id } : {});
|
|
464
|
+
} catch {
|
|
465
|
+
return reply(res, 500, rpcError(ErrorCode.InternalError, 'Internal server error'));
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
handler.closeAll = async () => {
|
|
470
|
+
for (const id of [...sessions.keys()]) await closeSession(id);
|
|
471
|
+
};
|
|
472
|
+
Object.defineProperty(handler, 'sessionCount', { get: () => sessions.size });
|
|
473
|
+
return handler;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
module.exports = { createInMemoryTransportPair, createStdioServerTransport, createStreamableHttpClientTransport, createStreamableHttpHandler, readServerSentEvents };
|