@jini-ai/mcp 0.7.1 → 0.7.3-next.1
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 +1 -1
- package/dist/agent-install/antigravity/install.d.ts +15 -0
- package/dist/agent-install/antigravity/install.js +15 -0
- package/dist/agent-install/claude/install.d.ts +4 -0
- package/dist/agent-install/claude/install.js +11 -0
- package/dist/agent-install/cline/install.d.ts +4 -0
- package/dist/agent-install/cline/install.js +7 -0
- package/dist/agent-install/codex/install.d.ts +4 -0
- package/dist/agent-install/codex/install.js +10 -0
- package/dist/agent-install/cursor/install.d.ts +4 -0
- package/dist/agent-install/cursor/install.js +4 -0
- package/dist/agent-install/hermes/install.d.ts +4 -0
- package/dist/agent-install/hermes/install.js +26 -0
- package/dist/agent-install/index.d.ts +1 -1
- package/dist/agent-install/install.d.ts +1 -11
- package/dist/agent-install/install.js +29 -167
- package/dist/agent-install/kimi/install.d.ts +4 -0
- package/dist/agent-install/kimi/install.js +10 -0
- package/dist/agent-install/openclaw/install.d.ts +4 -0
- package/dist/agent-install/openclaw/install.js +4 -0
- package/dist/agent-install/opencode/install.d.ts +4 -0
- package/dist/agent-install/opencode/install.js +7 -0
- package/dist/agent-install/owned-json-install.d.ts +7 -0
- package/dist/agent-install/owned-json-install.js +4 -4
- package/dist/agent-install/pi/install.d.ts +4 -0
- package/dist/agent-install/pi/install.js +13 -0
- package/dist/agent-install/planner-shared.d.ts +40 -0
- package/dist/agent-install/planner-shared.js +52 -0
- package/dist/agent-install/trae/install.d.ts +4 -0
- package/dist/agent-install/trae/install.js +7 -0
- package/dist/agent-install/vibe/install.d.ts +4 -0
- package/dist/agent-install/vibe/install.js +30 -0
- package/dist/bin/serve.js +5 -3
- package/dist/client/client.js +11 -7
- package/dist/core/claude/config.d.ts +21 -0
- package/dist/core/claude/config.js +29 -0
- package/dist/core/config-shared.d.ts +27 -0
- package/dist/core/config-shared.js +64 -0
- package/dist/core/config.d.ts +60 -81
- package/dist/core/config.js +33 -192
- package/dist/core/opencode/config.d.ts +39 -0
- package/dist/core/opencode/config.js +74 -0
- package/dist/core/tokens.d.ts +38 -25
- package/dist/core/tokens.js +23 -54
- package/dist/federation/adapter.http.d.ts +8 -5
- package/dist/federation/adapter.http.js +12 -8
- package/dist/federation/admissions.d.ts +36 -0
- package/dist/federation/admissions.js +34 -0
- package/dist/federation/approvals/call-confirmation.js +2 -2
- package/dist/federation/approvals/remembered-approval.d.ts +11 -2
- package/dist/federation/approvals/remembered-approval.js +11 -8
- package/dist/federation/approvals/revocation-reason.d.ts +3 -1
- package/dist/federation/approvals/revocation-reason.js +1 -1
- package/dist/federation/approvals/revocation.js +3 -3
- package/dist/federation/approvals/scope-option.d.ts +3 -1
- package/dist/federation/approvals/scope-option.js +1 -1
- package/dist/federation/bootstrap.d.ts +1 -1
- package/dist/federation/bootstrap.js +4 -5
- package/dist/federation/config.d.ts +1 -1
- package/dist/federation/hosted/access.d.ts +53 -1
- package/dist/federation/hosted/access.js +94 -0
- package/dist/federation/hosted/connection-gate.js +1 -1
- package/dist/federation/hosted/index.d.ts +11 -3
- package/dist/federation/hosted/index.js +9 -3
- package/dist/federation/hosted/pinned-capability.d.ts +91 -0
- package/dist/federation/hosted/pinned-capability.js +73 -0
- package/dist/federation/hosted/probe.d.ts +67 -0
- package/dist/federation/hosted/probe.js +99 -0
- package/dist/federation/hosted/revocation.d.ts +5 -2
- package/dist/federation/hosted/revocation.js +1 -1
- package/dist/federation/hosted/store-config.d.ts +43 -0
- package/dist/federation/hosted/store-config.js +209 -0
- package/dist/federation/hosted/store-credentials.d.ts +74 -0
- package/dist/federation/hosted/store-credentials.js +228 -0
- package/dist/federation/hosted/store-input.d.ts +55 -0
- package/dist/federation/hosted/store-input.js +232 -0
- package/dist/federation/hosted/store-oauth-fields.d.ts +26 -0
- package/dist/federation/hosted/store-oauth-fields.js +246 -0
- package/dist/federation/hosted/store-view.d.ts +49 -0
- package/dist/federation/hosted/store-view.js +112 -0
- package/dist/federation/hosted/store.d.ts +13 -180
- package/dist/federation/hosted/store.js +33 -1252
- package/dist/federation/hosted/store.memory.d.ts +26 -1
- package/dist/federation/hosted/store.memory.js +71 -22
- package/dist/federation/hosted/store.save.d.ts +39 -0
- package/dist/federation/hosted/store.save.js +63 -0
- package/dist/federation/hosted/vault.d.ts +79 -1
- package/dist/federation/hosted/vault.js +107 -0
- package/dist/federation/hosted/vocabulary.d.ts +1 -1
- package/dist/federation/hosted/vocabulary.js +1 -1
- package/dist/federation/index.d.ts +1 -0
- package/dist/federation/index.js +1 -0
- package/dist/federation/mcp-protocol.d.ts +1 -1
- package/dist/federation/mcp-protocol.js +1 -1
- package/dist/federation/ports.d.ts +2 -2
- package/dist/federation/refusal-notice.d.ts +1 -1
- package/dist/federation/refusal-notice.js +1 -1
- package/dist/federation/registrations.d.ts +6 -6
- package/dist/federation/registrations.js +1 -1
- package/dist/federation/reload.js +37 -36
- package/dist/federation/stdio/adapter.stdio.js +27 -20
- package/dist/federation/stdio/default-connect.d.ts +2 -5
- package/dist/federation/stdio/default-connect.js +2 -1
- package/dist/federation/stdio/index.d.ts +1 -0
- package/dist/federation/stdio/index.js +1 -0
- package/dist/federation/stdio/smoke.d.ts +62 -0
- package/dist/federation/stdio/smoke.js +156 -0
- package/dist/federation/trust.d.ts +2 -2
- package/dist/federation/trust.js +4 -4
- package/dist/index.d.ts +3 -4
- package/dist/index.js +1 -1
- package/dist/server/adapters/sdk-server.d.ts +88 -0
- package/dist/server/adapters/sdk-server.js +27 -0
- package/dist/server/{sdk-transport.d.ts → adapters/sdk-transport.d.ts} +3 -3
- package/dist/server/{sdk-transport.js → adapters/sdk-transport.js} +2 -2
- package/dist/server/adapters/sdk-wire.d.ts +16 -0
- package/dist/server/adapters/sdk-wire.js +16 -0
- package/dist/server/call-progress.d.ts +48 -0
- package/dist/server/call-progress.js +60 -0
- package/dist/server/http-tool-server.adapter.js +209 -196
- package/dist/server/index.d.ts +1 -0
- package/dist/server/loopback-fetch.d.ts +5 -0
- package/dist/server/loopback-fetch.js +48 -0
- package/dist/server/resource-protocol.d.ts +1 -1
- package/dist/server/run-tool-host.js +3 -1
- package/dist/server/stdio-hosting.d.ts +8 -12
- package/dist/server/stdio-hosting.js +135 -126
- package/dist/server/tool-arguments.d.ts +9 -1
- package/dist/server/tool-arguments.js +18 -4
- package/dist/server/tool-protocol.d.ts +15 -3
- package/dist/server/tool-protocol.js +18 -21
- package/dist/server/tool-result-pages.js +37 -28
- package/dist/server/tool-server.d.ts +8 -46
- package/dist/server/tool-server.js +138 -128
- package/dist/server/tools/component-catalog-tools.d.ts +2 -2
- package/dist/server/tools/component-catalog-tools.js +2 -2
- package/dist/server/tools/delegated-tool.js +74 -57
- package/dist/server/tools/run-tools.d.ts +5 -5
- package/dist/server/tools/run-tools.js +5 -5
- package/dist/server/tools/tool-catalog-tools.d.ts +2 -2
- package/dist/server/tools/tool-catalog-tools.js +35 -12
- package/package.json +8 -9
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module @jini-ai/mcp/server/loopback-fetch
|
|
3
|
+
* A `fetch`-shaped client for the loopback daemon over `node:http`, with no timeout of its own.
|
|
4
|
+
* Global `fetch` (undici) gives up when response headers take over 300 000 ms, which ends a tool call
|
|
5
|
+
* that waits on a person. Here only the caller's `AbortSignal` ends a request. Any other URL goes to
|
|
6
|
+
* `fallback` (default: the global `fetch`, read per call). No new dependency.
|
|
7
|
+
*/
|
|
8
|
+
import { request } from 'node:http';
|
|
9
|
+
import { Readable } from 'node:stream';
|
|
10
|
+
import { isLoopbackHostname } from '@jini-ai/core/net';
|
|
11
|
+
/** A response with one of these statuses has no body; `Response` refuses to be built with one. */
|
|
12
|
+
const hasNoBody = ({ status }) => [101, 204, 205, 304].includes(status);
|
|
13
|
+
function toUrl({ input }) {
|
|
14
|
+
return new URL(typeof input === 'string' || input instanceof URL ? input : input.url);
|
|
15
|
+
}
|
|
16
|
+
function sendOverHttp({ url, init }) {
|
|
17
|
+
const { signal } = init;
|
|
18
|
+
if (typeof init.body !== 'string' && init.body != null)
|
|
19
|
+
throw new TypeError('loopback fetch sends only string bodies');
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
if (signal?.aborted) {
|
|
22
|
+
reject(signal.reason);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const outgoing = request(url, { method: init.method ?? 'GET', headers: Object.fromEntries(new Headers(init.headers)), ...(signal ? { signal } : {}) }, incoming => {
|
|
26
|
+
const headers = new Headers();
|
|
27
|
+
for (const [name, value] of Object.entries(incoming.headers))
|
|
28
|
+
for (const item of [value ?? []].flat())
|
|
29
|
+
headers.append(name, item);
|
|
30
|
+
const status = incoming.statusCode ?? 502;
|
|
31
|
+
const body = hasNoBody({ status }) ? null : Readable.toWeb(incoming);
|
|
32
|
+
resolve(new Response(body, { status, statusText: incoming.statusMessage ?? '', headers }));
|
|
33
|
+
});
|
|
34
|
+
// Same rejections as `fetch`: the signal's reason on abort, else 'fetch failed' carrying the socket error as its cause.
|
|
35
|
+
outgoing.on('error', error => reject(signal?.aborted ? signal.reason : new TypeError('fetch failed', { cause: error })));
|
|
36
|
+
outgoing.end(init.body ?? undefined);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
/** @returns A fetch that reaches an `http:` loopback URL without a header wait and hands every other URL to `fallback`. */
|
|
40
|
+
export function createLoopbackFetch(_required = {}, { fallback } = {}) {
|
|
41
|
+
return (input, init = {}) => {
|
|
42
|
+
const url = toUrl({ input });
|
|
43
|
+
if (url.protocol !== 'http:' || !isLoopbackHostname({ hostname: url.hostname }))
|
|
44
|
+
return (fallback ?? fetch)(input, init);
|
|
45
|
+
return sendOverHttp({ url, init });
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=loopback-fetch.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ReadResourceResult, Resource } from '
|
|
1
|
+
import type { ReadResourceResult, Resource } from './adapters/sdk-wire.js';
|
|
2
2
|
import type { McpToolContext } from './tool-protocol.js';
|
|
3
3
|
/** What one resource's `read` returns before this module wraps it into the MCP wire shape. */
|
|
4
4
|
export interface McpResourceReadResult {
|
|
@@ -94,7 +94,9 @@ async function resolveStartupTools({ toolIds, resolveBaseUrl, serverOptions }) {
|
|
|
94
94
|
baseUrl: await resolveBaseUrl(),
|
|
95
95
|
fetchImpl: serverOptions.fetchImpl ?? fetch,
|
|
96
96
|
...definedOnly({ authHeaders: serverOptions.authHeaders, diagnosticToolIds: serverOptions.diagnosticToolIds }),
|
|
97
|
-
|
|
97
|
+
// Collection only: the exposure built later from `descriptors` decides what is published, and the
|
|
98
|
+
// describe result this answers is discarded, so nothing here is promised to a caller.
|
|
99
|
+
publishTool: async ({ descriptor }) => { descriptors.push(descriptor); return { skipped: 'not-found' }; },
|
|
98
100
|
};
|
|
99
101
|
for (const id of new Set(toolIds))
|
|
100
102
|
await describeToolTool.handler({ args: { id }, ctx });
|
|
@@ -24,23 +24,19 @@ export declare function createStdioHosting({ stdin, stdout, options }: {
|
|
|
24
24
|
stdin: Readable;
|
|
25
25
|
stdout: Writable;
|
|
26
26
|
};
|
|
27
|
-
|
|
28
|
-
guardTransport({ transport }: {
|
|
27
|
+
guardTransport: ({ transport }: {
|
|
29
28
|
transport: McpTransportLike;
|
|
30
|
-
})
|
|
31
|
-
|
|
32
|
-
track<T>({ task, signal }: {
|
|
29
|
+
}) => void;
|
|
30
|
+
track: <T>(required: {
|
|
33
31
|
task: () => Promise<T>;
|
|
34
32
|
signal: AbortSignal | undefined;
|
|
35
|
-
})
|
|
36
|
-
|
|
37
|
-
responseWritten({ result }: {
|
|
33
|
+
}) => Promise<T>;
|
|
34
|
+
responseWritten: ({ result }: {
|
|
38
35
|
result: Promise<unknown>;
|
|
39
|
-
})
|
|
40
|
-
|
|
41
|
-
watch({ close }: {
|
|
36
|
+
}) => Promise<void>;
|
|
37
|
+
watch: ({ close }: {
|
|
42
38
|
close: () => void;
|
|
43
|
-
})
|
|
39
|
+
}) => void;
|
|
44
40
|
/** Idempotent detach; queued handlers that have not started are skipped.
|
|
45
41
|
* @returns The first recorded failure, which the run rejects with. */
|
|
46
42
|
dispose(): Promise<{
|
|
@@ -7,7 +7,7 @@ import { once } from 'node:events';
|
|
|
7
7
|
import { Transform, Writable } from 'node:stream';
|
|
8
8
|
import { setImmediate } from 'node:timers/promises';
|
|
9
9
|
import { boundedMessage } from './adapters/stdio-codec.js';
|
|
10
|
-
import { resolveSdkTransport } from './sdk-transport.js';
|
|
10
|
+
import { resolveSdkTransport } from './adapters/sdk-transport.js';
|
|
11
11
|
/** Validate the opt-in limit before construction performs any I/O. */
|
|
12
12
|
export function validateFrameLimit({ maxFrameBytes }) {
|
|
13
13
|
if (maxFrameBytes === undefined)
|
|
@@ -53,147 +53,156 @@ function createGuardedStreams({ stdin, stdout, options: { maxFrameBytes, serial,
|
|
|
53
53
|
stdin.pipe(input.guard);
|
|
54
54
|
return { input, output, streams: { stdin: input?.guard ?? stdin, stdout: output ?? stdout } };
|
|
55
55
|
}
|
|
56
|
+
function listen({ state, emitter, event, fn }) {
|
|
57
|
+
emitter.on(event, fn);
|
|
58
|
+
state.removers.push(() => emitter.off(event, fn));
|
|
59
|
+
}
|
|
60
|
+
function fail({ state, error }) {
|
|
61
|
+
state.failure ??= { error };
|
|
62
|
+
state.closeTransport?.();
|
|
63
|
+
}
|
|
64
|
+
async function writesDone({ output }) {
|
|
65
|
+
while (output && output.writableLength > 0)
|
|
66
|
+
await once(output, 'drain');
|
|
67
|
+
}
|
|
68
|
+
/** Yield so SDK dispatch reaches handlers/sends, then wait until tracked writes complete. */
|
|
69
|
+
async function flushWrites(state) {
|
|
70
|
+
await setImmediate();
|
|
71
|
+
await writesDone(state);
|
|
72
|
+
}
|
|
73
|
+
async function drainInput(state) {
|
|
74
|
+
try {
|
|
75
|
+
await flushWrites(state);
|
|
76
|
+
while (state.inFlight.size > 0) {
|
|
77
|
+
await Promise.allSettled([...state.inFlight]);
|
|
78
|
+
await flushWrites(state);
|
|
79
|
+
}
|
|
80
|
+
if (state.input?.hasTail())
|
|
81
|
+
state.failure ??= { error: new Error('MCP stdin ended with an unterminated frame') };
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
state.failure ??= { error };
|
|
85
|
+
}
|
|
86
|
+
state.closeTransport?.();
|
|
87
|
+
}
|
|
88
|
+
/** Bound outgoing frames on the SDK transport this run created. Narrow fakes have no send. */
|
|
89
|
+
function guardTransport(state, transport) {
|
|
90
|
+
const { maxFrameBytes } = state.options;
|
|
91
|
+
const sdk = resolveSdkTransport({ transport });
|
|
92
|
+
if (maxFrameBytes === undefined || typeof sdk.send !== 'function')
|
|
93
|
+
return;
|
|
94
|
+
const send = sdk.send.bind(sdk);
|
|
95
|
+
sdk.send = (message, sendOptions) => {
|
|
96
|
+
let bounded;
|
|
97
|
+
try {
|
|
98
|
+
bounded = boundedMessage({ message, maxFrameBytes });
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
fail({ state, error });
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
return send(bounded, sendOptions);
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** Serial mode starts each handler only after the previous one settles and its response is written. */
|
|
108
|
+
function trackTask(state, { task, signal }) {
|
|
109
|
+
const serial = state.options.serial ?? false;
|
|
110
|
+
// Behind another request, yield first so the SDK can send that request's response.
|
|
111
|
+
const behind = state.inFlight.size > 0;
|
|
112
|
+
const run = async () => {
|
|
113
|
+
if (serial)
|
|
114
|
+
await (behind ? flushWrites(state) : writesDone(state));
|
|
115
|
+
if (state.stopped || signal?.aborted)
|
|
116
|
+
throw new Error('MCP request cancelled');
|
|
117
|
+
return task();
|
|
118
|
+
};
|
|
119
|
+
const result = serial ? state.tail.then(run) : run();
|
|
120
|
+
const settled = result.then(() => { }, () => { });
|
|
121
|
+
state.inFlight.add(settled);
|
|
122
|
+
void settled.then(() => state.inFlight.delete(settled));
|
|
123
|
+
if (serial)
|
|
124
|
+
state.tail = settled;
|
|
125
|
+
return result;
|
|
126
|
+
}
|
|
127
|
+
/** Settles once `result` settled and its response write completed, or the run stopped; never rejects. */
|
|
128
|
+
async function awaitResponseWritten({ output, stop }, { result }) {
|
|
129
|
+
await result.then(() => { }, () => { });
|
|
130
|
+
await setImmediate();
|
|
131
|
+
// Abortable unlike writesDone: a write still pending at dispose never drains.
|
|
132
|
+
try {
|
|
133
|
+
while (output && output.writableLength > 0)
|
|
134
|
+
await once(output, 'drain', { signal: stop.signal });
|
|
135
|
+
}
|
|
136
|
+
catch { /* run stopped */ }
|
|
137
|
+
}
|
|
138
|
+
/** Install EOF handling once connected; a failure recorded during connect closes at once. */
|
|
139
|
+
function watchEof({ state, close }) {
|
|
140
|
+
const { input, stdin } = state;
|
|
141
|
+
state.closeTransport = close;
|
|
142
|
+
if (state.failure)
|
|
143
|
+
return close();
|
|
144
|
+
if (state.options.eof !== 'drain' || !input) {
|
|
145
|
+
listen({ state, emitter: stdin, event: 'end', fn: close });
|
|
146
|
+
listen({ state, emitter: stdin, event: 'close', fn: close });
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
// The guard ends only after the SDK consumed every buffered frame.
|
|
150
|
+
listen({ state, emitter: input.guard, event: 'end', fn: () => void drainInput(state) });
|
|
151
|
+
listen({
|
|
152
|
+
state,
|
|
153
|
+
emitter: stdin,
|
|
154
|
+
event: 'close',
|
|
155
|
+
fn: () => { if (!stdin.readableEnded)
|
|
156
|
+
close(); },
|
|
157
|
+
});
|
|
158
|
+
// Embedding transports may not consume the guarded readable; still observe its end.
|
|
159
|
+
input.guard.resume();
|
|
160
|
+
if (input.guard.readableEnded)
|
|
161
|
+
void drainInput(state);
|
|
162
|
+
}
|
|
163
|
+
async function disposeRun(state) {
|
|
164
|
+
const { input, stdin, output } = state;
|
|
165
|
+
state.stopped = true;
|
|
166
|
+
state.stop.abort();
|
|
167
|
+
state.closeTransport = undefined;
|
|
168
|
+
if (input) {
|
|
169
|
+
stdin.unpipe(input.guard);
|
|
170
|
+
input.guard.destroy();
|
|
171
|
+
}
|
|
172
|
+
output?.destroy();
|
|
173
|
+
// One failed write errors this wrapper and then the borrowed stdout in later turns;
|
|
174
|
+
// keep observing until both have reported, then restore the host's own listeners.
|
|
175
|
+
await setImmediate();
|
|
176
|
+
for (const remove of state.removers)
|
|
177
|
+
remove();
|
|
178
|
+
return state.failure;
|
|
179
|
+
}
|
|
56
180
|
/**
|
|
57
181
|
* One run's guards. Stream failures and outgoing overflow are recorded and close the transport;
|
|
58
182
|
* the host's hold-open promise rejects with the first recorded failure.
|
|
59
183
|
* @complexity O(n) per n inbound bytes; O(r) bookkeeping for r accepted requests.
|
|
60
184
|
*/
|
|
61
185
|
export function createStdioHosting({ stdin, stdout, options }) {
|
|
62
|
-
const { maxFrameBytes, serial = false } = options;
|
|
63
186
|
const { input, output, streams } = createGuardedStreams({ stdin, stdout, options });
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
let failure;
|
|
68
|
-
let closeTransport;
|
|
69
|
-
let stopped = false;
|
|
70
|
-
const stop = new AbortController();
|
|
71
|
-
let disposed;
|
|
72
|
-
const listen = (emitter, event, fn) => {
|
|
73
|
-
emitter.on(event, fn);
|
|
74
|
-
removers.push(() => emitter.off(event, fn));
|
|
75
|
-
};
|
|
76
|
-
const fail = (error) => {
|
|
77
|
-
failure ??= { error };
|
|
78
|
-
closeTransport?.();
|
|
187
|
+
const state = {
|
|
188
|
+
stdin, options, input, output, inFlight: new Set(), removers: [], stop: new AbortController(),
|
|
189
|
+
tail: Promise.resolve(), failure: undefined, closeTransport: undefined, stopped: false, disposed: undefined,
|
|
79
190
|
};
|
|
80
191
|
for (const stream of [stdin, stdout, input?.guard, output])
|
|
81
192
|
if (stream)
|
|
82
|
-
listen(stream, 'error', fail);
|
|
83
|
-
async function writesDone() {
|
|
84
|
-
while (output && output.writableLength > 0)
|
|
85
|
-
await once(output, 'drain');
|
|
86
|
-
}
|
|
87
|
-
/** Yield so SDK dispatch reaches handlers/sends, then wait until tracked writes complete. */
|
|
88
|
-
async function flushWrites() {
|
|
89
|
-
await setImmediate();
|
|
90
|
-
await writesDone();
|
|
91
|
-
}
|
|
92
|
-
async function drain() {
|
|
93
|
-
try {
|
|
94
|
-
await flushWrites();
|
|
95
|
-
while (inFlight.size > 0) {
|
|
96
|
-
await Promise.allSettled([...inFlight]);
|
|
97
|
-
await flushWrites();
|
|
98
|
-
}
|
|
99
|
-
if (input?.hasTail())
|
|
100
|
-
failure ??= { error: new Error('MCP stdin ended with an unterminated frame') };
|
|
101
|
-
}
|
|
102
|
-
catch (error) {
|
|
103
|
-
failure ??= { error };
|
|
104
|
-
}
|
|
105
|
-
closeTransport?.();
|
|
106
|
-
}
|
|
193
|
+
listen({ state, emitter: stream, event: 'error', fn: (error) => fail({ state, error }) });
|
|
107
194
|
return {
|
|
108
195
|
/** The guarded pair handed to `createTransport` in place of the configured streams. */
|
|
109
196
|
streams,
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
return;
|
|
115
|
-
const send = sdk.send.bind(sdk);
|
|
116
|
-
sdk.send = (message, sendOptions) => {
|
|
117
|
-
let bounded;
|
|
118
|
-
try {
|
|
119
|
-
bounded = boundedMessage({ message, maxFrameBytes });
|
|
120
|
-
}
|
|
121
|
-
catch (error) {
|
|
122
|
-
fail(error);
|
|
123
|
-
throw error;
|
|
124
|
-
}
|
|
125
|
-
return send(bounded, sendOptions);
|
|
126
|
-
};
|
|
127
|
-
},
|
|
128
|
-
/** Serial mode starts each handler only after the previous one settles and its response is written. */
|
|
129
|
-
track({ task, signal }) {
|
|
130
|
-
// Behind another request, yield first so the SDK can send that request's response.
|
|
131
|
-
const behind = inFlight.size > 0;
|
|
132
|
-
const run = async () => {
|
|
133
|
-
if (serial)
|
|
134
|
-
await (behind ? flushWrites() : writesDone());
|
|
135
|
-
if (stopped || signal?.aborted)
|
|
136
|
-
throw new Error('MCP request cancelled');
|
|
137
|
-
return task();
|
|
138
|
-
};
|
|
139
|
-
const result = serial ? tail.then(run) : run();
|
|
140
|
-
const settled = result.then(() => { }, () => { });
|
|
141
|
-
inFlight.add(settled);
|
|
142
|
-
void settled.then(() => inFlight.delete(settled));
|
|
143
|
-
if (serial)
|
|
144
|
-
tail = settled;
|
|
145
|
-
return result;
|
|
146
|
-
},
|
|
147
|
-
/** Settles once `result` settled and its response write completed, or the run stopped; never rejects. */
|
|
148
|
-
async responseWritten({ result }) {
|
|
149
|
-
await result.then(() => { }, () => { });
|
|
150
|
-
await setImmediate();
|
|
151
|
-
// Abortable unlike writesDone: a write still pending at dispose never drains.
|
|
152
|
-
try {
|
|
153
|
-
while (output && output.writableLength > 0)
|
|
154
|
-
await once(output, 'drain', { signal: stop.signal });
|
|
155
|
-
}
|
|
156
|
-
catch { /* run stopped */ }
|
|
157
|
-
},
|
|
158
|
-
/** Install EOF handling once connected; a failure recorded during connect closes at once. */
|
|
159
|
-
watch({ close }) {
|
|
160
|
-
closeTransport = close;
|
|
161
|
-
if (failure)
|
|
162
|
-
return close();
|
|
163
|
-
if (options.eof !== 'drain' || !input) {
|
|
164
|
-
listen(stdin, 'end', close);
|
|
165
|
-
listen(stdin, 'close', close);
|
|
166
|
-
return;
|
|
167
|
-
}
|
|
168
|
-
// The guard ends only after the SDK consumed every buffered frame.
|
|
169
|
-
listen(input.guard, 'end', () => void drain());
|
|
170
|
-
listen(stdin, 'close', () => { if (!stdin.readableEnded)
|
|
171
|
-
close(); });
|
|
172
|
-
// Embedding transports may not consume the guarded readable; still observe its end.
|
|
173
|
-
input.guard.resume();
|
|
174
|
-
if (input.guard.readableEnded)
|
|
175
|
-
void drain();
|
|
176
|
-
},
|
|
197
|
+
guardTransport: ({ transport }) => guardTransport(state, transport),
|
|
198
|
+
track: (required) => trackTask(state, required),
|
|
199
|
+
responseWritten: ({ result }) => awaitResponseWritten(state, { result }),
|
|
200
|
+
watch: ({ close }) => watchEof({ state, close }),
|
|
177
201
|
/** Idempotent detach; queued handlers that have not started are skipped.
|
|
178
202
|
* @returns The first recorded failure, which the run rejects with. */
|
|
179
203
|
dispose() {
|
|
180
|
-
disposed ??= (
|
|
181
|
-
|
|
182
|
-
stop.abort();
|
|
183
|
-
closeTransport = undefined;
|
|
184
|
-
if (input) {
|
|
185
|
-
stdin.unpipe(input.guard);
|
|
186
|
-
input.guard.destroy();
|
|
187
|
-
}
|
|
188
|
-
output?.destroy();
|
|
189
|
-
// One failed write errors this wrapper and then the borrowed stdout in later turns;
|
|
190
|
-
// keep observing until both have reported, then restore the host's own listeners.
|
|
191
|
-
await setImmediate();
|
|
192
|
-
for (const remove of removers)
|
|
193
|
-
remove();
|
|
194
|
-
return failure;
|
|
195
|
-
})();
|
|
196
|
-
return disposed;
|
|
204
|
+
state.disposed ??= disposeRun(state);
|
|
205
|
+
return state.disposed;
|
|
197
206
|
},
|
|
198
207
|
};
|
|
199
208
|
}
|
|
@@ -19,6 +19,13 @@ export interface McpToolArgumentContract {
|
|
|
19
19
|
readonly foldIntoInput?: true;
|
|
20
20
|
/** Concrete registry tools reuse the core schema normalizer before MCP validation. */
|
|
21
21
|
readonly schemaInput?: true;
|
|
22
|
+
/**
|
|
23
|
+
* A local tool opts in to the declared `clamp` repair on its own schema: a property that sets
|
|
24
|
+
* `clamp: true` has an out-of-range number moved to its bound, with a note. This does not turn
|
|
25
|
+
* on `schemaInput` (which also changes the tool's refusal texts); registry tools get the clamp
|
|
26
|
+
* through the core normalizer and never need this flag.
|
|
27
|
+
*/
|
|
28
|
+
readonly clamp?: true;
|
|
22
29
|
};
|
|
23
30
|
}
|
|
24
31
|
/** Resolve this host's CLI decoration, preserving exact registered names and other servers.
|
|
@@ -60,7 +67,8 @@ export declare function withArgumentContract({ message, inputSchema }: {
|
|
|
60
67
|
export declare function argumentShapeMessage({ errors, inputSchema }: {
|
|
61
68
|
errors: readonly OutputUnit[];
|
|
62
69
|
inputSchema?: unknown;
|
|
63
|
-
}, { includeContract }?: {
|
|
70
|
+
}, { includeContract, isKnownTool }?: {
|
|
64
71
|
includeContract?: boolean;
|
|
72
|
+
isKnownTool?: (toolId: string) => boolean;
|
|
65
73
|
}): string;
|
|
66
74
|
//# sourceMappingURL=tool-arguments.d.ts.map
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { decodeToolInputObject, unwrapToolInputEnvelope } from '@jini-ai/core';
|
|
2
|
+
import { missingArgumentGuidance } from '@jini-ai/core/tool-input-repairs';
|
|
2
3
|
/** Resolve this host's CLI decoration, preserving exact registered names and other servers.
|
|
3
4
|
* @param required - Model-visible name, possibly prefixed by the Jini MCP client.
|
|
4
5
|
* @param options - Exact-name lookup when a local tool index is available.
|
|
@@ -128,14 +129,27 @@ function pointerToFieldPath({ instanceLocation }) {
|
|
|
128
129
|
* The supply/remove instruction for a `required` or `additionalProperties` error, whose message
|
|
129
130
|
* quotes the offending property name; `undefined` for any other error, or when no name is quoted.
|
|
130
131
|
*/
|
|
131
|
-
function namedFieldMessage({ error, path }) {
|
|
132
|
+
function namedFieldMessage({ error, path, inputSchema, isKnownTool }) {
|
|
132
133
|
if (error.keyword !== 'required' && error.keyword !== 'additionalProperties')
|
|
133
134
|
return undefined;
|
|
134
135
|
const field = error.error.match(/"(.*)"/)?.[1];
|
|
135
136
|
if (field === undefined)
|
|
136
137
|
return undefined;
|
|
137
138
|
const key = path ? `${path}.${field}` : field;
|
|
138
|
-
|
|
139
|
+
if (error.keyword !== 'required')
|
|
140
|
+
return `remove unknown argument \`${key}\``;
|
|
141
|
+
return `supply required argument \`${key}\`${obtainFromClause({ field, path, inputSchema }, isKnownTool === undefined ? {} : { isKnownTool })}`;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* `; list valid values with <tool>` for a top-level required argument whose schema declares `obtainFrom`
|
|
145
|
+
* and names a tool the run can see; empty otherwise. The validator already said the field is absent, so
|
|
146
|
+
* the guidance is read against an empty input and only this field's entry is used.
|
|
147
|
+
*/
|
|
148
|
+
function obtainFromClause({ field, path, inputSchema }, { isKnownTool } = {}) {
|
|
149
|
+
if (path !== '')
|
|
150
|
+
return '';
|
|
151
|
+
const entry = missingArgumentGuidance({ inputSchema, input: {} }, isKnownTool === undefined ? {} : { isKnownTool }).find(({ property }) => property === field);
|
|
152
|
+
return entry === undefined ? '' : `; list valid values with ${entry.toolId}`;
|
|
139
153
|
}
|
|
140
154
|
/** A complete small contract for repair diagnostics. Never truncate a schema into a misleading
|
|
141
155
|
* partial contract, including nested choices, batches and local refs. (Search hits carry only a
|
|
@@ -167,13 +181,13 @@ export function withArgumentContract({ message, inputSchema }, _options = {}) {
|
|
|
167
181
|
* @returns A field instruction plus a bounded contract when requested or needed for missing fields/items.
|
|
168
182
|
* @complexity O(e + p + s) for e errors, p path characters and s serialized schema bytes.
|
|
169
183
|
*/
|
|
170
|
-
export function argumentShapeMessage({ errors, inputSchema }, { includeContract = false } = {}) {
|
|
184
|
+
export function argumentShapeMessage({ errors, inputSchema }, { includeContract = false, isKnownTool } = {}) {
|
|
171
185
|
// Keep the additionalProperties diagnostic ahead of its generic false-schema child.
|
|
172
186
|
const error = errors.find((entry) => entry.keyword === 'required' || entry.keyword === 'additionalProperties' || entry.instanceLocation !== '#') ?? errors[0];
|
|
173
187
|
if (error === undefined)
|
|
174
188
|
return 'supply arguments matching the declared input schema';
|
|
175
189
|
const path = pointerToFieldPath({ instanceLocation: error.instanceLocation });
|
|
176
|
-
const message = namedFieldMessage({ error, path }) ?? `change \`${path || 'arguments'}\`: ${error.error}`;
|
|
190
|
+
const message = namedFieldMessage({ error, path, inputSchema, ...(isKnownTool === undefined ? {} : { isKnownTool }) }) ?? `change \`${path || 'arguments'}\`: ${error.error}`;
|
|
177
191
|
// Wrong keys also need the accepted names and units, not a sequence of remove/retry guesses.
|
|
178
192
|
if (!includeContract && !errors.some(entry => ['required', 'items'].includes(entry.keyword)))
|
|
179
193
|
return message;
|
|
@@ -45,9 +45,17 @@
|
|
|
45
45
|
* See docs/decisions/DR-002-protocol-resource-boundary.md.
|
|
46
46
|
*/
|
|
47
47
|
import { type ToolDescriptor } from '@jini-ai/core';
|
|
48
|
-
import type
|
|
48
|
+
import { type CallToolResult, type Tool } from './adapters/sdk-wire.js';
|
|
49
49
|
import { type McpToolArgumentContract } from './tool-arguments.js';
|
|
50
50
|
import { type DaemonRequestOptions } from './daemon-client.js';
|
|
51
|
+
/** Why a described tool was not published as its own tool: a full list, a full schema budget, or no such descriptor. */
|
|
52
|
+
export type ToolPublicationSkipReason = 'tool-limit' | 'schema-byte-limit' | 'not-found';
|
|
53
|
+
/** The outcome of publishing one described tool. */
|
|
54
|
+
export type ToolPublication = {
|
|
55
|
+
readonly wireName: string;
|
|
56
|
+
} | {
|
|
57
|
+
readonly skipped: ToolPublicationSkipReason;
|
|
58
|
+
};
|
|
51
59
|
/** What every tool handler receives alongside its parsed arguments. */
|
|
52
60
|
export interface McpToolContext {
|
|
53
61
|
/** Resolve MCP-local names through the hosting server; undefined leaves daemon dispatch intact. */
|
|
@@ -56,10 +64,14 @@ export interface McpToolContext {
|
|
|
56
64
|
input: Record<string, unknown>;
|
|
57
65
|
requireReadOnly: boolean;
|
|
58
66
|
}, optional?: Record<string, never>) => Promise<CallToolResult | undefined>;
|
|
59
|
-
/**
|
|
67
|
+
/**
|
|
68
|
+
* Publishes a successfully described, host-owned descriptor in this server run only, and says what happened:
|
|
69
|
+
* the wire name it is now called by (an already published tool answers with its existing name), or why it was
|
|
70
|
+
* not published, so the caller can tell the model to use the gateway instead of promising a tool that is not there.
|
|
71
|
+
*/
|
|
60
72
|
readonly publishTool?: (required: {
|
|
61
73
|
descriptor: ToolDescriptor;
|
|
62
|
-
}, optional?: Record<string, never>) => Promise<
|
|
74
|
+
}, optional?: Record<string, never>) => Promise<ToolPublication>;
|
|
63
75
|
/** Host registration metadata, supplied outside model-controlled arguments. */
|
|
64
76
|
readonly diagnosticToolIds?: readonly string[];
|
|
65
77
|
/** The resolved daemon HTTP base URL (no trailing slash), fixed for the lifetime of one server run. */
|
|
@@ -46,8 +46,10 @@
|
|
|
46
46
|
*/
|
|
47
47
|
import { batchOutcomeFor, normalizeToolInput, withNormalizationNotes } from '@jini-ai/core';
|
|
48
48
|
import { sanitizeUntrustedText } from '@jini-ai/core/text';
|
|
49
|
+
import { clampDeclaredBounds } from '@jini-ai/core/tool-input-repairs';
|
|
50
|
+
import { unknownToolSentence } from '@jini-ai/core/tool-call-text';
|
|
49
51
|
import { Validator } from '@cfworker/json-schema';
|
|
50
|
-
import {
|
|
52
|
+
import { isPassthroughContentBlock } from './adapters/sdk-wire.js';
|
|
51
53
|
import { argumentShapeMessage, isRecord, normalizeToolArguments, resolveMcpToolName, withArgumentContract } from './tool-arguments.js';
|
|
52
54
|
import { safeDiagnostic } from './daemon-client.js';
|
|
53
55
|
import { scopeNestedSchemaRefs } from './schema-ref-scope.js';
|
|
@@ -73,20 +75,6 @@ export function daemonCallOptions({ ctx }, _options = {}) {
|
|
|
73
75
|
...(ctx.signal !== undefined ? { signal: ctx.signal } : {}),
|
|
74
76
|
};
|
|
75
77
|
}
|
|
76
|
-
/**
|
|
77
|
-
* True when `block` is a well-formed MCP content block this module will pass through verbatim rather
|
|
78
|
-
* than JSON-stringify. Delegates to the pinned `@modelcontextprotocol/sdk`'s own `ContentBlockSchema`
|
|
79
|
-
* (the same union `CallToolResultSchema.content` is defined against) instead of a hand-maintained list
|
|
80
|
-
* of per-type shape checks — see this module's own doc for why that matters: a manually maintained
|
|
81
|
-
* allowlist only ever covers the block types someone remembered to add, so the *next* protocol content
|
|
82
|
-
* type (this SDK version already knows five: `text`, `image`, `audio`, `resource`, `resource_link`)
|
|
83
|
-
* would silently fall back to the stringify path exactly like `resource` did before this fix. A block
|
|
84
|
-
* that merely claims a recognized `type` but is missing/mistyping its required field(s) still fails
|
|
85
|
-
* `safeParse` and falls back to the stringify path rather than being forwarded malformed.
|
|
86
|
-
*/
|
|
87
|
-
function isPassthroughContentBlock(block) {
|
|
88
|
-
return ContentBlockSchema.safeParse(block).success;
|
|
89
|
-
}
|
|
90
78
|
/**
|
|
91
79
|
* True when `payload` is already a well-formed MCP content envelope safe to hand back to the client
|
|
92
80
|
* unchanged: a record whose `content` field is an array, and every entry in it is a recognized,
|
|
@@ -100,7 +88,13 @@ function isMcpContentEnvelope(payload) {
|
|
|
100
88
|
if (!isRecord(payload))
|
|
101
89
|
return false;
|
|
102
90
|
const content = payload['content'];
|
|
103
|
-
return Array.isArray(content) && content.every(isPassthroughContentBlock);
|
|
91
|
+
return Array.isArray(content) && content.every(block => isPassthroughContentBlock({ block }));
|
|
92
|
+
}
|
|
93
|
+
/** A payload is an error when it flags itself so or reports a failed batch outcome. */
|
|
94
|
+
function isErrorPayload({ payload }, _optional = {}) {
|
|
95
|
+
const outcome = batchOutcomeFor({ output: payload });
|
|
96
|
+
const flaggedError = typeof payload === 'object' && payload !== null && 'isError' in payload && payload.isError === true;
|
|
97
|
+
return flaggedError || outcome === 'partial_failure' || outcome === 'error';
|
|
104
98
|
}
|
|
105
99
|
/**
|
|
106
100
|
* Wraps a tool result as an MCP `CallToolResult`, preserving explicit errors and failed batch outcomes.
|
|
@@ -116,9 +110,7 @@ function isMcpContentEnvelope(payload) {
|
|
|
116
110
|
* envelope or batch; O(1) otherwise.
|
|
117
111
|
*/
|
|
118
112
|
export function okResult({ payload }) {
|
|
119
|
-
const
|
|
120
|
-
const flaggedError = typeof payload === 'object' && payload !== null && 'isError' in payload && payload.isError === true;
|
|
121
|
-
const isError = flaggedError || outcome === 'partial_failure' || outcome === 'error';
|
|
113
|
+
const isError = isErrorPayload({ payload });
|
|
122
114
|
if (isMcpContentEnvelope(payload)) {
|
|
123
115
|
return { content: payload.content,
|
|
124
116
|
...(isRecord(payload.structuredContent) ? { structuredContent: payload.structuredContent } : {}),
|
|
@@ -193,6 +185,11 @@ function validatorForTool(tool) {
|
|
|
193
185
|
*/
|
|
194
186
|
async function normalizeCallArguments({ tool, rawArgs }, _options = {}) {
|
|
195
187
|
const args = normalizeToolArguments({ tool, rawArgs });
|
|
188
|
+
if (tool.argumentNormalization?.clamp) {
|
|
189
|
+
// Local tools opt in to the clamp alone: the rest of their refusal texts stay as they are.
|
|
190
|
+
const clamped = clampDeclaredBounds({ input: args, inputSchema: tool.inputSchema });
|
|
191
|
+
return { args: clamped.input, notes: clamped.notes };
|
|
192
|
+
}
|
|
196
193
|
if (!tool.argumentNormalization?.schemaInput)
|
|
197
194
|
return { args, notes: [] };
|
|
198
195
|
const normalized = await normalizeToolInput({ input: args, registration: { descriptor: { id: tool.name, inputSchema: tool.inputSchema } } });
|
|
@@ -230,7 +227,7 @@ export async function handleToolCall({ name, tools, ctx }, { rawArgs } = {}) {
|
|
|
230
227
|
ctx = { ...ctx, diagnosticToolIds };
|
|
231
228
|
const tool = tools.get(resolveMcpToolName({ name }, { isRegistered: candidate => tools.has(candidate) }));
|
|
232
229
|
if (tool === undefined) {
|
|
233
|
-
return errorResult({ message:
|
|
230
|
+
return errorResult({ message: unknownToolSentence({ toolId: name, candidates: [...tools.keys()] }) });
|
|
234
231
|
}
|
|
235
232
|
// Normalization and schema validation share an error boundary; handlers run only afterward.
|
|
236
233
|
// See docs/decisions/DR-005-proxy-argument-shapes.md.
|
|
@@ -240,7 +237,7 @@ export async function handleToolCall({ name, tools, ctx }, { rawArgs } = {}) {
|
|
|
240
237
|
const { args, notes } = await normalizeCallArguments({ tool, rawArgs: rawArgs ?? {} });
|
|
241
238
|
const validation = validatorForTool(tool).validate(args);
|
|
242
239
|
if (!validation.valid) {
|
|
243
|
-
return errorResult({ message: `invalid arguments for ${tool.name}: ${sanitizeUntrustedText({ text: argumentShapeMessage({ errors: validation.errors, inputSchema: wireInputSchema(tool) }, { includeContract: tool.argumentNormalization?.schemaInput === true }) }, {
|
|
240
|
+
return errorResult({ message: `invalid arguments for ${tool.name}: ${sanitizeUntrustedText({ text: argumentShapeMessage({ errors: validation.errors, inputSchema: wireInputSchema(tool) }, { includeContract: tool.argumentNormalization?.schemaInput === true, isKnownTool: id => diagnosticToolIds.includes(id) }) }, {
|
|
244
241
|
diagnosticToolIds,
|
|
245
242
|
// A complete bounded contract must survive the default 500-character diagnostic cap.
|
|
246
243
|
maxLength: 4608,
|