@jini-ai/mcp 0.7.2 → 0.7.3-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/dist/agent-install/antigravity/install.d.ts +15 -0
  3. package/dist/agent-install/antigravity/install.js +15 -0
  4. package/dist/agent-install/claude/install.d.ts +4 -0
  5. package/dist/agent-install/claude/install.js +11 -0
  6. package/dist/agent-install/cline/install.d.ts +4 -0
  7. package/dist/agent-install/cline/install.js +7 -0
  8. package/dist/agent-install/codex/install.d.ts +4 -0
  9. package/dist/agent-install/codex/install.js +10 -0
  10. package/dist/agent-install/cursor/install.d.ts +4 -0
  11. package/dist/agent-install/cursor/install.js +4 -0
  12. package/dist/agent-install/hermes/install.d.ts +4 -0
  13. package/dist/agent-install/hermes/install.js +26 -0
  14. package/dist/agent-install/index.d.ts +1 -1
  15. package/dist/agent-install/install.d.ts +1 -11
  16. package/dist/agent-install/install.js +29 -167
  17. package/dist/agent-install/kimi/install.d.ts +4 -0
  18. package/dist/agent-install/kimi/install.js +10 -0
  19. package/dist/agent-install/openclaw/install.d.ts +4 -0
  20. package/dist/agent-install/openclaw/install.js +4 -0
  21. package/dist/agent-install/opencode/install.d.ts +4 -0
  22. package/dist/agent-install/opencode/install.js +7 -0
  23. package/dist/agent-install/owned-json-install.d.ts +7 -0
  24. package/dist/agent-install/owned-json-install.js +4 -4
  25. package/dist/agent-install/pi/install.d.ts +4 -0
  26. package/dist/agent-install/pi/install.js +13 -0
  27. package/dist/agent-install/planner-shared.d.ts +40 -0
  28. package/dist/agent-install/planner-shared.js +52 -0
  29. package/dist/agent-install/trae/install.d.ts +4 -0
  30. package/dist/agent-install/trae/install.js +7 -0
  31. package/dist/agent-install/vibe/install.d.ts +4 -0
  32. package/dist/agent-install/vibe/install.js +30 -0
  33. package/dist/bin/serve.js +5 -3
  34. package/dist/client/client.js +11 -7
  35. package/dist/core/claude/config.d.ts +21 -0
  36. package/dist/core/claude/config.js +29 -0
  37. package/dist/core/config-shared.d.ts +27 -0
  38. package/dist/core/config-shared.js +64 -0
  39. package/dist/core/config.d.ts +60 -81
  40. package/dist/core/config.js +33 -192
  41. package/dist/core/opencode/config.d.ts +39 -0
  42. package/dist/core/opencode/config.js +74 -0
  43. package/dist/core/tokens.d.ts +38 -25
  44. package/dist/core/tokens.js +23 -54
  45. package/dist/federation/adapter.http.d.ts +8 -5
  46. package/dist/federation/adapter.http.js +12 -8
  47. package/dist/federation/admissions.d.ts +36 -0
  48. package/dist/federation/admissions.js +34 -0
  49. package/dist/federation/approvals/call-confirmation.js +2 -2
  50. package/dist/federation/approvals/remembered-approval.d.ts +11 -2
  51. package/dist/federation/approvals/remembered-approval.js +11 -8
  52. package/dist/federation/approvals/revocation-reason.d.ts +3 -1
  53. package/dist/federation/approvals/revocation-reason.js +1 -1
  54. package/dist/federation/approvals/revocation.js +3 -3
  55. package/dist/federation/approvals/scope-option.d.ts +3 -1
  56. package/dist/federation/approvals/scope-option.js +1 -1
  57. package/dist/federation/bootstrap.d.ts +1 -1
  58. package/dist/federation/bootstrap.js +4 -5
  59. package/dist/federation/config.d.ts +1 -1
  60. package/dist/federation/hosted/access.d.ts +53 -1
  61. package/dist/federation/hosted/access.js +94 -0
  62. package/dist/federation/hosted/connection-gate.js +1 -1
  63. package/dist/federation/hosted/index.d.ts +11 -3
  64. package/dist/federation/hosted/index.js +9 -3
  65. package/dist/federation/hosted/pinned-capability.d.ts +91 -0
  66. package/dist/federation/hosted/pinned-capability.js +73 -0
  67. package/dist/federation/hosted/probe.d.ts +67 -0
  68. package/dist/federation/hosted/probe.js +99 -0
  69. package/dist/federation/hosted/revocation.d.ts +5 -2
  70. package/dist/federation/hosted/revocation.js +1 -1
  71. package/dist/federation/hosted/store-config.d.ts +43 -0
  72. package/dist/federation/hosted/store-config.js +209 -0
  73. package/dist/federation/hosted/store-credentials.d.ts +74 -0
  74. package/dist/federation/hosted/store-credentials.js +228 -0
  75. package/dist/federation/hosted/store-input.d.ts +55 -0
  76. package/dist/federation/hosted/store-input.js +232 -0
  77. package/dist/federation/hosted/store-oauth-fields.d.ts +26 -0
  78. package/dist/federation/hosted/store-oauth-fields.js +246 -0
  79. package/dist/federation/hosted/store-view.d.ts +49 -0
  80. package/dist/federation/hosted/store-view.js +112 -0
  81. package/dist/federation/hosted/store.d.ts +13 -180
  82. package/dist/federation/hosted/store.js +33 -1252
  83. package/dist/federation/hosted/store.memory.d.ts +26 -1
  84. package/dist/federation/hosted/store.memory.js +71 -22
  85. package/dist/federation/hosted/store.save.d.ts +39 -0
  86. package/dist/federation/hosted/store.save.js +63 -0
  87. package/dist/federation/hosted/vault.d.ts +79 -1
  88. package/dist/federation/hosted/vault.js +107 -0
  89. package/dist/federation/hosted/vocabulary.d.ts +1 -1
  90. package/dist/federation/hosted/vocabulary.js +1 -1
  91. package/dist/federation/index.d.ts +1 -0
  92. package/dist/federation/index.js +1 -0
  93. package/dist/federation/mcp-protocol.d.ts +1 -1
  94. package/dist/federation/mcp-protocol.js +1 -1
  95. package/dist/federation/ports.d.ts +2 -2
  96. package/dist/federation/refusal-notice.d.ts +1 -1
  97. package/dist/federation/refusal-notice.js +1 -1
  98. package/dist/federation/registrations.d.ts +6 -6
  99. package/dist/federation/registrations.js +1 -1
  100. package/dist/federation/reload.js +37 -36
  101. package/dist/federation/stdio/adapter.stdio.js +27 -20
  102. package/dist/federation/stdio/default-connect.d.ts +2 -5
  103. package/dist/federation/stdio/default-connect.js +2 -1
  104. package/dist/federation/stdio/index.d.ts +1 -0
  105. package/dist/federation/stdio/index.js +1 -0
  106. package/dist/federation/stdio/smoke.d.ts +62 -0
  107. package/dist/federation/stdio/smoke.js +156 -0
  108. package/dist/federation/trust.d.ts +2 -2
  109. package/dist/federation/trust.js +4 -4
  110. package/dist/index.d.ts +3 -4
  111. package/dist/index.js +1 -1
  112. package/dist/server/adapters/sdk-server.d.ts +88 -0
  113. package/dist/server/adapters/sdk-server.js +27 -0
  114. package/dist/server/{sdk-transport.d.ts → adapters/sdk-transport.d.ts} +3 -3
  115. package/dist/server/{sdk-transport.js → adapters/sdk-transport.js} +2 -2
  116. package/dist/server/adapters/sdk-wire.d.ts +16 -0
  117. package/dist/server/adapters/sdk-wire.js +16 -0
  118. package/dist/server/call-progress.d.ts +48 -0
  119. package/dist/server/call-progress.js +60 -0
  120. package/dist/server/http-tool-server.adapter.js +209 -196
  121. package/dist/server/index.d.ts +1 -0
  122. package/dist/server/loopback-fetch.d.ts +5 -0
  123. package/dist/server/loopback-fetch.js +48 -0
  124. package/dist/server/resource-protocol.d.ts +1 -1
  125. package/dist/server/run-tool-host.js +3 -1
  126. package/dist/server/stdio-hosting.d.ts +8 -12
  127. package/dist/server/stdio-hosting.js +135 -126
  128. package/dist/server/tool-arguments.d.ts +9 -1
  129. package/dist/server/tool-arguments.js +18 -4
  130. package/dist/server/tool-protocol.d.ts +15 -3
  131. package/dist/server/tool-protocol.js +18 -21
  132. package/dist/server/tool-result-pages.js +37 -28
  133. package/dist/server/tool-server.d.ts +8 -46
  134. package/dist/server/tool-server.js +138 -128
  135. package/dist/server/tools/component-catalog-tools.d.ts +2 -2
  136. package/dist/server/tools/component-catalog-tools.js +2 -2
  137. package/dist/server/tools/delegated-tool.js +74 -57
  138. package/dist/server/tools/run-tools.d.ts +5 -5
  139. package/dist/server/tools/run-tools.js +5 -5
  140. package/dist/server/tools/tool-catalog-tools.d.ts +2 -2
  141. package/dist/server/tools/tool-catalog-tools.js +35 -12
  142. package/package.json +8 -9
  143. package/dist/core/oauth.d.ts +0 -274
  144. package/dist/core/oauth.js +0 -667
  145. package/dist/core/secure-write.d.ts +0 -17
  146. package/dist/core/secure-write.js +0 -72
@@ -3,6 +3,13 @@ const INLINE_CHARS = 12000;
3
3
  const MAX_STORED_CHARS = 8_000_000;
4
4
  const MAX_RESULTS = 32;
5
5
  const SMALL_BLOCK_CHARS = 1024;
6
+ /** `limit` opts in to the clamp repair: a page size above the maximum is read at the maximum, with a note. */
7
+ const READ_TOOL_RESULT_INPUT_SCHEMA = {
8
+ type: 'object', required: ['resultId'], additionalProperties: false, properties: {
9
+ resultId: { type: 'string', minLength: 1 }, offset: { type: 'integer', minimum: 0 },
10
+ limit: { type: 'integer', minimum: 1, maximum: 8000, clamp: true },
11
+ },
12
+ };
6
13
  /** Keep large text in this MCP run rather than a CLI-owned spill file outside the site sandbox.
7
14
  * Text is paged losslessly; image/resource blocks and result error flags pass through unchanged.
8
15
  * @param _required No required configuration; one instance belongs to one server run.
@@ -26,13 +33,19 @@ export function createToolResultPages(_required, { generateId = randomUUID, } =
26
33
  storedChars += text.length;
27
34
  return id;
28
35
  }
29
- const tool = {
36
+ const tool = createReadToolResult(saved);
37
+ return {
38
+ tool,
39
+ project({ result }) { return projectToolResult(result, save); },
40
+ clear() { saved.clear(); storedChars = 0; },
41
+ };
42
+ }
43
+ function createReadToolResult(saved) {
44
+ return {
30
45
  name: 'read_tool_result',
31
46
  description: 'Read a page of a saved oversized tool result in this run. Use resultId from the tool response, offset (default 0), and limit (default 4000, max 8000). Returns one text block: JSON cursor metadata on its first line, then exact result text. Follow nextOffset until null. Unknown/evicted IDs fail; repeat the original tool with a narrower query. Never read CLI spill files with Bash.',
32
- inputSchema: { type: 'object', required: ['resultId'], additionalProperties: false, properties: {
33
- resultId: { type: 'string', minLength: 1 }, offset: { type: 'integer', minimum: 0 },
34
- limit: { type: 'integer', minimum: 1, maximum: 8000 },
35
- } },
47
+ inputSchema: READ_TOOL_RESULT_INPUT_SCHEMA,
48
+ argumentNormalization: { clamp: true },
36
49
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
37
50
  handler({ args }) {
38
51
  const resultId = args['resultId'];
@@ -47,28 +60,24 @@ export function createToolResultPages(_required, { generateId = randomUUID, } =
47
60
  return { content: [{ type: 'text', text: `${JSON.stringify(cursor)}\n${text.slice(offset, end)}` }] };
48
61
  },
49
62
  };
50
- return {
51
- tool,
52
- project({ result }) {
53
- const texts = result.content.flatMap(block => block.type === 'text' ? [block.text] : []);
54
- const totalChars = texts.reduce((sum, text) => sum + text.length, 0);
55
- if (totalChars <= INLINE_CHARS)
56
- return result;
57
- // Keep small metadata blocks inline; page medium blocks too when their combined size spills.
58
- const retained = texts.filter(text => text.length > SMALL_BLOCK_CHARS);
59
- const retainedChars = retained.reduce((sum, text) => sum + text.length, 0);
60
- // Admit one response atomically so its later blocks cannot evict its earlier block IDs.
61
- if (retained.length > MAX_RESULTS || retainedChars > MAX_STORED_CHARS || totalChars - retainedChars > 4000)
62
- return { isError: true, content: [{ type: 'text',
63
- text: 'Tool result exceeds the saved-result limit. Repeat the original tool call with a narrower query. Never use Bash to read CLI spill files.' }] };
64
- return { ...result, content: result.content.map(block => {
65
- if (block.type !== 'text' || block.text.length <= SMALL_BLOCK_CHARS)
66
- return block;
67
- const resultId = save(block.text);
68
- return { ...block, text: `Saved tool result (${block.text.length} characters). Read it with read_tool_result(${JSON.stringify({ resultId, offset: 0 })}); follow nextOffset until null. Never use Bash or shell commands to read saved tool results.` };
69
- }) };
70
- },
71
- clear() { saved.clear(); storedChars = 0; },
72
- };
63
+ }
64
+ function projectToolResult(result, save) {
65
+ const texts = result.content.flatMap(block => block.type === 'text' ? [block.text] : []);
66
+ const totalChars = texts.reduce((sum, text) => sum + text.length, 0);
67
+ if (totalChars <= INLINE_CHARS)
68
+ return result;
69
+ // Keep small metadata blocks inline; page medium blocks too when their combined size spills.
70
+ const retained = texts.filter(text => text.length > SMALL_BLOCK_CHARS);
71
+ const retainedChars = retained.reduce((sum, text) => sum + text.length, 0);
72
+ // Admit one response atomically so its later blocks cannot evict its earlier block IDs.
73
+ if (retained.length > MAX_RESULTS || retainedChars > MAX_STORED_CHARS || totalChars - retainedChars > 4000)
74
+ return { isError: true, content: [{ type: 'text',
75
+ text: 'Tool result exceeds the saved-result limit. Repeat the original tool call with a narrower query. Never use Bash to read CLI spill files.' }] };
76
+ return { ...result, content: result.content.map(block => {
77
+ if (block.type !== 'text' || block.text.length <= SMALL_BLOCK_CHARS)
78
+ return block;
79
+ const resultId = save(block.text);
80
+ return { ...block, text: `Saved tool result (${block.text.length} characters). Read it with read_tool_result(${JSON.stringify({ resultId, offset: 0 })}); follow nextOffset until null. Never use Bash or shell commands to read saved tool results.` };
81
+ }) };
73
82
  }
74
83
  //# sourceMappingURL=tool-result-pages.js.map
@@ -9,57 +9,16 @@
9
9
  */
10
10
  import type { Readable, Writable } from 'node:stream';
11
11
  import { type ToolDescriptor } from '@jini-ai/core';
12
+ import type { Logger } from '@jini-ai/core/primitives';
12
13
  import type { McpTransportLike } from './ports.js';
13
14
  export type { McpTransportLike } from './ports.js';
14
- import type { ServerOptions } from '@modelcontextprotocol/sdk/server/index.js';
15
- import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
16
- import type { CallToolResult, Implementation, ListResourcesResult, ListToolsResult, ReadResourceResult } from '@modelcontextprotocol/sdk/types.js';
15
+ import { type McpServerLike, type SdkServerInfo, type SdkServerOptions } from './adapters/sdk-server.js';
16
+ import { type CallProgressScheduler } from './call-progress.js';
17
17
  import { type McpResourceDef } from './resource-protocol.js';
18
18
  import { type McpToolDef } from './tool-protocol.js';
19
19
  import { type CreateExecuteDelegatedToolToolOptions } from './tools/delegated-tool.js';
20
20
  import { type McpMessageRelay } from './message-relay.js';
21
21
  import { type StdioHostingOptions } from './stdio-hosting.js';
22
- /** Object-shaped server port. The default adapter translates it to the SDK interface. */
23
- export interface McpServerLike {
24
- setRequestHandler(args: {
25
- schema: typeof ListToolsRequestSchema;
26
- handler: () => Promise<ListToolsResult>;
27
- }): void;
28
- setRequestHandler(args: {
29
- schema: typeof CallToolRequestSchema;
30
- handler: (requiredArgs: {
31
- request: {
32
- params: {
33
- name: string;
34
- arguments?: Record<string, unknown>;
35
- };
36
- };
37
- }, optionalArgs?: {
38
- extra?: {
39
- signal?: AbortSignal;
40
- };
41
- }) => Promise<CallToolResult>;
42
- }): void;
43
- setRequestHandler(args: {
44
- schema: typeof ListResourcesRequestSchema;
45
- handler: () => Promise<ListResourcesResult>;
46
- }): void;
47
- setRequestHandler(args: {
48
- schema: typeof ReadResourceRequestSchema;
49
- handler: (requiredArgs: {
50
- request: {
51
- params: {
52
- uri: string;
53
- };
54
- };
55
- }) => Promise<ReadResourceResult>;
56
- }): void;
57
- connect(args: {
58
- transport: McpTransportLike;
59
- }): Promise<void>;
60
- /** Optional for static embeddings; required when delegated publication is enabled. */
61
- sendToolListChanged?(required: Record<string, never>, optional?: Record<string, never>): Promise<void>;
62
- }
63
22
  /** Required identity, tool surface, and daemon URL resolver. */
64
23
  export interface McpToolServerRequiredArgs {
65
24
  /** Identity advertised to the MCP client during initialization. */
@@ -84,6 +43,9 @@ export interface McpToolServerOptions extends StdioHostingOptions {
84
43
  readonly resources?: readonly McpResourceDef[];
85
44
  /** Free-text guidance surfaced to the MCP client alongside the tool list. Optional — omit for a caller with nothing to add beyond each tool's own `description`. */
86
45
  readonly instructions?: string;
46
+ /** Progress keepalive of a slow `tools/call`: its timer (default real timers) and the log for a failed send (default stderr console). */
47
+ readonly progressScheduler?: CallProgressScheduler;
48
+ readonly logger?: Logger;
87
49
  /** Idle-exit window in ms. Defaults to {@link DEFAULT_IDLE_MS}. */
88
50
  readonly idleMs?: number;
89
51
  /** Defaults to the global `fetch`; threaded into every tool call's {@link McpToolContext}. */
@@ -100,8 +62,8 @@ export interface McpToolServerOptions extends StdioHostingOptions {
100
62
  readonly stdout?: Writable;
101
63
  /** Test/embedding seam: builds the underlying `Server`. Defaults to the real `@modelcontextprotocol/sdk` `Server`. */
102
64
  readonly createServer?: (args: {
103
- info: Implementation;
104
- options: ServerOptions;
65
+ info: SdkServerInfo;
66
+ options: SdkServerOptions;
105
67
  }) => McpServerLike;
106
68
  /** Test/embedding seam: builds the underlying transport. Defaults to the real `StdioServerTransport`. */
107
69
  readonly createTransport?: (requiredArgs: Record<string, never>, optionalArgs?: {
@@ -1,9 +1,7 @@
1
1
  import { createToolExposure } from '@jini-ai/core';
2
- import { adaptSdkTransport, resolveSdkTransport } from './sdk-transport.js';
3
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
- import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
2
+ import { defaultCreateServer, defaultCreateTransport, bindSdkToolHandlers, bindSdkResourceHandlers } from './adapters/sdk-server.js';
6
3
  import { createMcpIdleExitController } from '../client/client.js';
4
+ import { startCallProgress } from './call-progress.js';
7
5
  import { buildResourceIndex, handleResourceRead, resourcesToList } from './resource-protocol.js';
8
6
  import { buildToolIndex, handleToolCall, toolsToList } from './tool-protocol.js';
9
7
  import { createTypedDelegatedToolTool } from './tools/delegated-tool.js';
@@ -13,18 +11,6 @@ import { prependRunUserMessages } from './message-relay.js';
13
11
  import { createStdioHosting, validateFrameLimit, wantsStdioHosting } from './stdio-hosting.js';
14
12
  /** Auto-exit an idle server after this long without tool activity. */
15
13
  const DEFAULT_IDLE_MS = 30 * 60 * 1000;
16
- // SDK objects remain behind these adapters; hosts implement the object-shaped ports above.
17
- function defaultCreateServer({ info, options }) {
18
- const server = new Server(info, options);
19
- return {
20
- setRequestHandler: (({ schema, handler }) => server.setRequestHandler(schema, (request, extra) => handler({ request }, { extra }))),
21
- connect: ({ transport }) => server.connect(resolveSdkTransport({ transport })),
22
- sendToolListChanged: () => server.sendToolListChanged(),
23
- };
24
- }
25
- function defaultCreateTransport(_requiredArgs, { stdin, stdout } = {}) {
26
- return adaptSdkTransport({ transport: new StdioServerTransport(stdin, stdout) });
27
- }
28
14
  /**
29
15
  * The tool context shared by every call in one run: the resolved daemon URL without its trailing
30
16
  * slash (coerced to a string for JS hosts that ignore the contract), the configured or global
@@ -104,6 +90,20 @@ function createHostedTransport({ createTransport, options, hosting }) {
104
90
  hosting.guardTransport({ transport });
105
91
  return transport;
106
92
  }
93
+ /**
94
+ * What a promotion did for one tool: the wire name it is published under (also when it was already
95
+ * published before this call), or the reason it was skipped. The model is told this, so a full list is
96
+ * never silent.
97
+ * @returns The name from the exposure's own snapshot, never one derived from the id.
98
+ * @complexity O(n) for n published tools; no effects.
99
+ */
100
+ function publicationOutcome({ toolId, delta }) {
101
+ const skipped = delta.skipped.find(entry => entry.toolId === toolId);
102
+ if (skipped !== undefined)
103
+ return { skipped: skipped.reason };
104
+ const published = delta.snapshot.tools.find(tool => tool.descriptor.id === toolId);
105
+ return published === undefined ? { skipped: 'not-found' } : { wireName: published.wireName };
106
+ }
107
107
  /**
108
108
  * Own only the MCP projection/dispatch index. F0 owns immutable exposure, and the daemon catalog
109
109
  * supplies each descriptor; the temporary source below is not another definition catalog.
@@ -143,19 +143,124 @@ function createToolPublisher({ index, server, options }) {
143
143
  }
144
144
  if (delta.added.length > 0)
145
145
  notificationPending = true;
146
- if (!notificationPending)
147
- return;
148
- // Clear before awaiting: a concurrent promotion must retain its own unsent notification.
149
- notificationPending = false;
150
- try {
151
- await notify({});
152
- }
153
- catch (error) {
154
- notificationPending = true;
155
- throw error;
146
+ if (notificationPending) {
147
+ // Clear before awaiting: a concurrent promotion must retain its own unsent notification.
148
+ notificationPending = false;
149
+ try {
150
+ await notify({});
151
+ }
152
+ catch (error) {
153
+ notificationPending = true;
154
+ throw error;
155
+ }
156
156
  }
157
+ return publicationOutcome({ toolId: descriptor.id, delta });
158
+ };
159
+ }
160
+ function createCallToolHandler(cfg, { toolIndex, ctx, resultPages }) {
161
+ const { options } = cfg;
162
+ return async ({ request }, { extra } = {}) => {
163
+ const callContext = extra?.signal !== undefined ? { ...ctx, signal: extra.signal } : ctx;
164
+ let checkedMessages = resolveMcpToolName({ name: request.params.name }, { isRegistered: candidate => toolIndex.has(candidate) }) === 'check_messages';
165
+ const callLocalTool = async ({ name, input, requireReadOnly }, _optional = {}) => {
166
+ const tool = toolIndex.get(resolveMcpToolName({ name }, { isRegistered: candidate => toolIndex.has(candidate) }));
167
+ if (!tool)
168
+ return undefined;
169
+ if (requireReadOnly && tool.annotations?.readOnlyHint !== true) {
170
+ throw new Error(`Tool "${name}" is not declared read-only; use execute_delegated_tool.`);
171
+ }
172
+ checkedMessages = tool.name === 'check_messages';
173
+ // Keep nesting bounded: a local gateway's own handler receives the base context.
174
+ return handleToolCall({ name, tools: toolIndex, ctx: callContext }, { rawArgs: input });
175
+ };
176
+ // One keepalive per CLI call: the nested `callLocalTool` await above is deliberately not wrapped.
177
+ const progress = startCallProgress({ extra }, { scheduler: options.progressScheduler, logger: options.logger });
178
+ const result = await handleToolCall({ name: request.params.name, tools: toolIndex,
179
+ ctx: { ...callContext, callLocalTool } }, { rawArgs: request.params.arguments }).finally(progress.stop);
180
+ // A delegated check must keep its trusted nonce and claim only once, just like a direct check.
181
+ const readableResult = checkedMessages ? result : (resultPages?.project({ result }) ?? result);
182
+ if (!options.messageRelay || checkedMessages)
183
+ return readableResult;
184
+ return prependRunUserMessages({ result: readableResult, relay: options.messageRelay, ctx: callContext });
157
185
  };
158
186
  }
187
+ function registerResourceHandlers({ cfg, server, ctx, withActivity }) {
188
+ const { resources, resourceIndex } = cfg;
189
+ bindSdkResourceHandlers({ server,
190
+ listResources: withActivity(async () => ({ resources: resourcesToList({ resources }) })),
191
+ readResource: () => withActivity(async ({ request }) => handleResourceRead({ uri: request.params.uri, resources: resourceIndex, ctx })),
192
+ });
193
+ }
194
+ /** Install the shared tool/resource dispatch for either hosting lifecycle. O(tools + resources).
195
+ * Transport closure clears result pages; the returned cleanup also covers failed stdio closure.
196
+ */
197
+ async function connectHost(cfg, { transport, withActivity }) {
198
+ const { requiredArgs, options, resources } = cfg;
199
+ const resultPages = options.resultPaging ? createToolResultPages({}) : undefined;
200
+ const toolIndex = buildToolIndex({ tools: [...requiredArgs.tools, ...(resultPages ? [resultPages.tool] : [])] });
201
+ let ctx = buildToolContext({ resolvedBaseUrl: await requiredArgs.resolveBaseUrl() }, options);
202
+ const server = cfg.createServer({
203
+ info: { name: requiredArgs.name, version: requiredArgs.version },
204
+ options: {
205
+ capabilities: { tools: options.delegatedTools ? { listChanged: true } : {}, ...(resources.length > 0 ? { resources: {} } : {}) },
206
+ ...(options.instructions !== undefined ? { instructions: options.instructions } : {}),
207
+ },
208
+ });
209
+ const publishTool = createToolPublisher({ index: toolIndex, server, options: options.delegatedTools });
210
+ if (publishTool)
211
+ ctx = { ...ctx, publishTool };
212
+ bindSdkToolHandlers({ server,
213
+ listTools: withActivity(async () => ({ tools: toolsToList({ tools: [...toolIndex.values()] }) })),
214
+ callTool: () => withActivity(createCallToolHandler(cfg, { toolIndex, ctx, resultPages })),
215
+ });
216
+ if (resources.length > 0)
217
+ registerResourceHandlers({ cfg, server, ctx, withActivity });
218
+ try {
219
+ await server.connect({ transport });
220
+ const onclose = transport.onclose;
221
+ transport.onclose = () => { onclose?.(); resultPages?.clear({}); };
222
+ return () => resultPages?.clear({});
223
+ }
224
+ catch (error) {
225
+ resultPages?.clear({});
226
+ throw error;
227
+ }
228
+ }
229
+ /** Own the stdio lifecycle: idle exit, optional hosting guards and teardown. */
230
+ async function runOwnedTransport(cfg) {
231
+ const { options } = cfg;
232
+ let closeTransportForIdle = null;
233
+ const idleExit = createMcpIdleExitController({
234
+ idleMs: options.idleMs ?? DEFAULT_IDLE_MS,
235
+ onIdle: () => closeTransportForIdle?.(),
236
+ });
237
+ const hosting = hostingForOptions(options);
238
+ const withActivity = createActivityTracker({ idleExit, hosting });
239
+ const transport = createHostedTransport({ createTransport: cfg.createTransport, options, hosting });
240
+ let disposeHost;
241
+ try {
242
+ closeTransportForIdle = () => {
243
+ void transport.close({}).catch(() => { });
244
+ };
245
+ disposeHost = await connectHost(cfg, { transport, withActivity });
246
+ // `connect()` sets `transport.onmessage` to its own protocol-dispatch handler; wrap it so
247
+ // every inbound message also counts as activity for the idle-exit timer, without losing
248
+ // the SDK's own routing.
249
+ const sdkOnMessage = transport.onmessage;
250
+ transport.onmessage = ({ message }) => {
251
+ idleExit.noteActivity({});
252
+ sdkOnMessage?.({ message });
253
+ };
254
+ await waitForTransportClose({ transport, idleExit, hosting, stdin: options.stdin ?? process.stdin });
255
+ }
256
+ finally {
257
+ disposeHost?.();
258
+ idleExit.dispose({});
259
+ if (hosting)
260
+ void hosting.dispose();
261
+ closeTransportForIdle = null;
262
+ }
263
+ }
159
264
  /**
160
265
  * Builds an MCP tool host with a stdio lifecycle unless run() receives an explicit transport.
161
266
  * Construction is synchronous and cheap (validates tool-name uniqueness via
@@ -168,113 +273,18 @@ export function createMcpToolServer(requiredArgs, options = {}) {
168
273
  // Validate eagerly, but keep the mutable dispatch index inside run() so re-runs are isolated.
169
274
  buildToolIndex({ tools: requiredArgs.tools });
170
275
  const resources = options.resources ?? [];
171
- const resourceIndex = buildResourceIndex({ resources });
172
- const createServer = options.createServer ?? defaultCreateServer;
173
- const createTransport = options.createTransport ?? defaultCreateTransport;
174
- /** Install the shared tool/resource dispatch for either hosting lifecycle. O(tools + resources).
175
- * Transport closure clears result pages; the returned cleanup also covers failed stdio closure.
176
- */
177
- async function connectHost({ transport, withActivity }) {
178
- const resultPages = options.resultPaging ? createToolResultPages({}) : undefined;
179
- const toolIndex = buildToolIndex({ tools: [...requiredArgs.tools, ...(resultPages ? [resultPages.tool] : [])] });
180
- let ctx = buildToolContext({ resolvedBaseUrl: await requiredArgs.resolveBaseUrl() }, options);
181
- const server = createServer({
182
- info: { name: requiredArgs.name, version: requiredArgs.version },
183
- options: {
184
- capabilities: { tools: options.delegatedTools ? { listChanged: true } : {}, ...(resources.length > 0 ? { resources: {} } : {}) },
185
- ...(options.instructions !== undefined ? { instructions: options.instructions } : {}),
186
- },
187
- });
188
- const publishTool = createToolPublisher({ index: toolIndex, server, options: options.delegatedTools });
189
- if (publishTool)
190
- ctx = { ...ctx, publishTool };
191
- server.setRequestHandler({
192
- schema: ListToolsRequestSchema,
193
- handler: withActivity(async () => ({ tools: toolsToList({ tools: [...toolIndex.values()] }) })),
194
- });
195
- server.setRequestHandler({
196
- schema: CallToolRequestSchema,
197
- handler: withActivity(async ({ request }, { extra } = {}) => {
198
- const callContext = extra?.signal !== undefined ? { ...ctx, signal: extra.signal } : ctx;
199
- let checkedMessages = resolveMcpToolName({ name: request.params.name }, { isRegistered: candidate => toolIndex.has(candidate) }) === 'check_messages';
200
- const callLocalTool = async ({ name, input, requireReadOnly }, _optional = {}) => {
201
- const tool = toolIndex.get(resolveMcpToolName({ name }, { isRegistered: candidate => toolIndex.has(candidate) }));
202
- if (!tool)
203
- return undefined;
204
- if (requireReadOnly && tool.annotations?.readOnlyHint !== true) {
205
- throw new Error(`Tool "${name}" is not declared read-only; use execute_delegated_tool.`);
206
- }
207
- checkedMessages = tool.name === 'check_messages';
208
- // Keep nesting bounded: a local gateway's own handler receives the base context.
209
- return handleToolCall({ name, tools: toolIndex, ctx: callContext }, { rawArgs: input });
210
- };
211
- const result = await handleToolCall({ name: request.params.name, tools: toolIndex,
212
- ctx: { ...callContext, callLocalTool } }, { rawArgs: request.params.arguments });
213
- // A delegated check must keep its trusted nonce and claim only once, just like a direct check.
214
- const readableResult = checkedMessages ? result : (resultPages?.project({ result }) ?? result);
215
- if (!options.messageRelay || checkedMessages)
216
- return readableResult;
217
- return prependRunUserMessages({ result: readableResult, relay: options.messageRelay, ctx: callContext });
218
- }),
219
- });
220
- if (resources.length > 0) {
221
- server.setRequestHandler({
222
- schema: ListResourcesRequestSchema,
223
- handler: withActivity(async () => ({ resources: resourcesToList({ resources }) })),
224
- });
225
- server.setRequestHandler({
226
- schema: ReadResourceRequestSchema,
227
- handler: withActivity(async ({ request }) => handleResourceRead({ uri: request.params.uri, resources: resourceIndex, ctx })),
228
- });
229
- }
230
- try {
231
- await server.connect({ transport });
232
- const onclose = transport.onclose;
233
- transport.onclose = () => { onclose?.(); resultPages?.clear({}); };
234
- return () => resultPages?.clear({});
235
- }
236
- catch (error) {
237
- resultPages?.clear({});
238
- throw error;
239
- }
240
- }
276
+ const cfg = {
277
+ requiredArgs, options, resources, resourceIndex: buildResourceIndex({ resources }),
278
+ createServer: options.createServer ?? defaultCreateServer,
279
+ createTransport: options.createTransport ?? defaultCreateTransport,
280
+ };
241
281
  return {
242
282
  async run({ transport: externalTransport }) {
243
283
  if (externalTransport) {
244
- await connectHost({ transport: externalTransport, withActivity: handler => async (...args) => handler(...args) });
284
+ await connectHost(cfg, { transport: externalTransport, withActivity: handler => async (...args) => handler(...args) });
245
285
  return;
246
286
  }
247
- let closeTransportForIdle = null;
248
- const idleExit = createMcpIdleExitController({
249
- idleMs: options.idleMs ?? DEFAULT_IDLE_MS,
250
- onIdle: () => closeTransportForIdle?.(),
251
- });
252
- const hosting = hostingForOptions(options);
253
- const withActivity = createActivityTracker({ idleExit, hosting });
254
- const transport = createHostedTransport({ createTransport, options, hosting });
255
- let disposeHost;
256
- try {
257
- closeTransportForIdle = () => {
258
- void transport.close({}).catch(() => { });
259
- };
260
- disposeHost = await connectHost({ transport, withActivity });
261
- // `connect()` sets `transport.onmessage` to its own protocol-dispatch handler; wrap it so
262
- // every inbound message also counts as activity for the idle-exit timer, without losing
263
- // the SDK's own routing.
264
- const sdkOnMessage = transport.onmessage;
265
- transport.onmessage = ({ message }) => {
266
- idleExit.noteActivity({});
267
- sdkOnMessage?.({ message });
268
- };
269
- await waitForTransportClose({ transport, idleExit, hosting, stdin: options.stdin ?? process.stdin });
270
- }
271
- finally {
272
- disposeHost?.();
273
- idleExit.dispose({});
274
- if (hosting)
275
- void hosting.dispose();
276
- closeTransportForIdle = null;
277
- }
287
+ await runOwnedTransport(cfg);
278
288
  },
279
289
  };
280
290
  }
@@ -1,7 +1,7 @@
1
1
  import { type McpToolDef } from '../tool-protocol.js';
2
- /** `search_components` -> `GET /api/components/search` (`packages/http-kit/src/component-catalog.ts`'s `componentCatalogSearchRoute`). */
2
+ /** `search_components` -> `GET /api/components/search` (`packages/daemon/src/http/component-catalog.ts`'s `componentCatalogSearchRoute`). */
3
3
  export declare const searchComponentsTool: McpToolDef;
4
- /** `describe_component` -> `GET /api/components/:id` (`packages/http-kit/src/component-catalog.ts`'s `componentCatalogDescribeRoute`). */
4
+ /** `describe_component` -> `GET /api/components/:id` (`packages/daemon/src/http/component-catalog.ts`'s `componentCatalogDescribeRoute`). */
5
5
  export declare const describeComponentTool: McpToolDef;
6
6
  /** Both component-catalog discovery tools, ready to pass as `createMcpToolServer`'s `tools` option. */
7
7
  export declare const COMPONENT_CATALOG_TOOLS: readonly McpToolDef[];
@@ -17,7 +17,7 @@ const READ_ANNOTATIONS = {
17
17
  idempotentHint: true,
18
18
  openWorldHint: false,
19
19
  };
20
- /** `search_components` -> `GET /api/components/search` (`packages/http-kit/src/component-catalog.ts`'s `componentCatalogSearchRoute`). */
20
+ /** `search_components` -> `GET /api/components/search` (`packages/daemon/src/http/component-catalog.ts`'s `componentCatalogSearchRoute`). */
21
21
  export const searchComponentsTool = {
22
22
  name: 'search_components',
23
23
  description: 'Search the registered interactive-UI component catalog. Returns ranked {id, provider, capabilities, description, score} candidates only — no propsSchema, so this stays cheap to call broadly. Call describe_component on the 1-3 candidates that look right before composing an A2UI or MCP-UI message that names one. Describe what interaction or data shape you need, not a component class name — e.g. "tabular list of records the user can click into" rather than "table".',
@@ -48,7 +48,7 @@ export const searchComponentsTool = {
48
48
  return data.hits;
49
49
  },
50
50
  };
51
- /** `describe_component` -> `GET /api/components/:id` (`packages/http-kit/src/component-catalog.ts`'s `componentCatalogDescribeRoute`). */
51
+ /** `describe_component` -> `GET /api/components/:id` (`packages/daemon/src/http/component-catalog.ts`'s `componentCatalogDescribeRoute`). */
52
52
  export const describeComponentTool = {
53
53
  name: 'describe_component',
54
54
  description: 'Get the full descriptor for one component id found via search_components — provider, capabilities, and propsSchema. Paid for only on the candidates that survive search.',