@providerkit/agents 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/LICENSE-APACHE-2.0 +202 -0
  2. package/README.md +2108 -52
  3. package/THIRD_PARTY_NOTICES.md +521 -0
  4. package/dist/a2a/auth.d.ts +10 -0
  5. package/dist/a2a/auth.d.ts.map +1 -0
  6. package/dist/a2a/auth.js +52 -0
  7. package/dist/a2a/auth.js.map +1 -0
  8. package/dist/a2a/client.d.ts +74 -0
  9. package/dist/a2a/client.d.ts.map +1 -0
  10. package/dist/a2a/client.js +601 -0
  11. package/dist/a2a/client.js.map +1 -0
  12. package/dist/a2a/index.d.ts +22 -0
  13. package/dist/a2a/index.d.ts.map +1 -0
  14. package/dist/a2a/index.js +11 -0
  15. package/dist/a2a/index.js.map +1 -0
  16. package/dist/a2a/memory-runs.d.ts +62 -0
  17. package/dist/a2a/memory-runs.d.ts.map +1 -0
  18. package/dist/a2a/memory-runs.js +349 -0
  19. package/dist/a2a/memory-runs.js.map +1 -0
  20. package/dist/a2a/policy.d.ts +15 -0
  21. package/dist/a2a/policy.d.ts.map +1 -0
  22. package/dist/a2a/policy.js +114 -0
  23. package/dist/a2a/policy.js.map +1 -0
  24. package/dist/a2a/push.d.ts +34 -0
  25. package/dist/a2a/push.d.ts.map +1 -0
  26. package/dist/a2a/push.js +180 -0
  27. package/dist/a2a/push.js.map +1 -0
  28. package/dist/a2a/remote.d.ts +155 -0
  29. package/dist/a2a/remote.d.ts.map +1 -0
  30. package/dist/a2a/remote.js +1196 -0
  31. package/dist/a2a/remote.js.map +1 -0
  32. package/dist/a2a/server.d.ts +110 -0
  33. package/dist/a2a/server.d.ts.map +1 -0
  34. package/dist/a2a/server.js +1139 -0
  35. package/dist/a2a/server.js.map +1 -0
  36. package/dist/a2a/signing.d.ts +21 -0
  37. package/dist/a2a/signing.d.ts.map +1 -0
  38. package/dist/a2a/signing.js +305 -0
  39. package/dist/a2a/signing.js.map +1 -0
  40. package/dist/a2a/tasks.d.ts +88 -0
  41. package/dist/a2a/tasks.d.ts.map +1 -0
  42. package/dist/a2a/tasks.js +170 -0
  43. package/dist/a2a/tasks.js.map +1 -0
  44. package/dist/a2a/wire.d.ts +267 -0
  45. package/dist/a2a/wire.d.ts.map +1 -0
  46. package/dist/a2a/wire.js +1202 -0
  47. package/dist/a2a/wire.js.map +1 -0
  48. package/dist/background-types.d.ts +76 -0
  49. package/dist/background-types.d.ts.map +1 -0
  50. package/dist/background-types.js +2 -0
  51. package/dist/background-types.js.map +1 -0
  52. package/dist/child.d.ts +25 -0
  53. package/dist/child.d.ts.map +1 -0
  54. package/dist/child.js +129 -0
  55. package/dist/child.js.map +1 -0
  56. package/dist/code-driver.d.ts +40 -0
  57. package/dist/code-driver.d.ts.map +1 -0
  58. package/dist/code-driver.js +2 -0
  59. package/dist/code-driver.js.map +1 -0
  60. package/dist/code-mode.d.ts +3 -0
  61. package/dist/code-mode.d.ts.map +1 -0
  62. package/dist/code-mode.js +2 -0
  63. package/dist/code-mode.js.map +1 -0
  64. package/dist/code-script.d.ts +3 -0
  65. package/dist/code-script.d.ts.map +1 -0
  66. package/dist/code-script.js +149 -0
  67. package/dist/code-script.js.map +1 -0
  68. package/dist/code.d.ts +75 -0
  69. package/dist/code.d.ts.map +1 -0
  70. package/dist/code.js +326 -0
  71. package/dist/code.js.map +1 -0
  72. package/dist/compaction.d.ts +15 -0
  73. package/dist/compaction.d.ts.map +1 -0
  74. package/dist/compaction.js +168 -0
  75. package/dist/compaction.js.map +1 -0
  76. package/dist/delegation.d.ts +85 -16
  77. package/dist/delegation.d.ts.map +1 -1
  78. package/dist/delegation.js +240 -106
  79. package/dist/delegation.js.map +1 -1
  80. package/dist/evals/driver.d.ts +10 -0
  81. package/dist/evals/driver.d.ts.map +1 -0
  82. package/dist/evals/driver.js +192 -0
  83. package/dist/evals/driver.js.map +1 -0
  84. package/dist/evals/journal.d.ts +26 -0
  85. package/dist/evals/journal.d.ts.map +1 -0
  86. package/dist/evals/journal.js +483 -0
  87. package/dist/evals/journal.js.map +1 -0
  88. package/dist/evals/judge.d.ts +31 -0
  89. package/dist/evals/judge.d.ts.map +1 -0
  90. package/dist/evals/judge.js +142 -0
  91. package/dist/evals/judge.js.map +1 -0
  92. package/dist/evals/report.d.ts +38 -0
  93. package/dist/evals/report.d.ts.map +1 -0
  94. package/dist/evals/report.js +241 -0
  95. package/dist/evals/report.js.map +1 -0
  96. package/dist/evals/runner.d.ts +24 -0
  97. package/dist/evals/runner.d.ts.map +1 -0
  98. package/dist/evals/runner.js +655 -0
  99. package/dist/evals/runner.js.map +1 -0
  100. package/dist/evals/scorers.d.ts +36 -0
  101. package/dist/evals/scorers.d.ts.map +1 -0
  102. package/dist/evals/scorers.js +259 -0
  103. package/dist/evals/scorers.js.map +1 -0
  104. package/dist/evals/simulation.d.ts +7 -0
  105. package/dist/evals/simulation.d.ts.map +1 -0
  106. package/dist/evals/simulation.js +38 -0
  107. package/dist/evals/simulation.js.map +1 -0
  108. package/dist/evals/testing.d.ts +36 -0
  109. package/dist/evals/testing.d.ts.map +1 -0
  110. package/dist/evals/testing.js +87 -0
  111. package/dist/evals/testing.js.map +1 -0
  112. package/dist/evals/trajectory.d.ts +11 -0
  113. package/dist/evals/trajectory.d.ts.map +1 -0
  114. package/dist/evals/trajectory.js +180 -0
  115. package/dist/evals/trajectory.js.map +1 -0
  116. package/dist/evals/types.d.ts +431 -0
  117. package/dist/evals/types.d.ts.map +1 -0
  118. package/dist/evals/types.js +4 -0
  119. package/dist/evals/types.js.map +1 -0
  120. package/dist/evals.d.ts +14 -0
  121. package/dist/evals.d.ts.map +1 -0
  122. package/dist/evals.js +9 -0
  123. package/dist/evals.js.map +1 -0
  124. package/dist/extensions.d.ts +33 -0
  125. package/dist/extensions.d.ts.map +1 -0
  126. package/dist/extensions.js +188 -0
  127. package/dist/extensions.js.map +1 -0
  128. package/dist/handoff.d.ts +58 -0
  129. package/dist/handoff.d.ts.map +1 -0
  130. package/dist/handoff.js +160 -0
  131. package/dist/handoff.js.map +1 -0
  132. package/dist/index.d.ts +14 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +8 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/input.d.ts +42 -0
  137. package/dist/input.d.ts.map +1 -0
  138. package/dist/input.js +266 -0
  139. package/dist/input.js.map +1 -0
  140. package/dist/mcp.d.ts +77 -0
  141. package/dist/mcp.d.ts.map +1 -0
  142. package/dist/mcp.js +505 -0
  143. package/dist/mcp.js.map +1 -0
  144. package/dist/memory-store.d.ts +11 -0
  145. package/dist/memory-store.d.ts.map +1 -0
  146. package/dist/memory-store.js +272 -0
  147. package/dist/memory-store.js.map +1 -0
  148. package/dist/memory.d.ts +212 -0
  149. package/dist/memory.d.ts.map +1 -0
  150. package/dist/memory.js +613 -0
  151. package/dist/memory.js.map +1 -0
  152. package/dist/otel.d.ts +74 -0
  153. package/dist/otel.d.ts.map +1 -0
  154. package/dist/otel.js +427 -0
  155. package/dist/otel.js.map +1 -0
  156. package/dist/progress.d.ts +17 -0
  157. package/dist/progress.d.ts.map +1 -0
  158. package/dist/progress.js +193 -0
  159. package/dist/progress.js.map +1 -0
  160. package/dist/quickjs.d.ts +19 -0
  161. package/dist/quickjs.d.ts.map +1 -0
  162. package/dist/quickjs.js +519 -0
  163. package/dist/quickjs.js.map +1 -0
  164. package/dist/recovery.d.ts +10 -0
  165. package/dist/recovery.d.ts.map +1 -0
  166. package/dist/recovery.js +62 -0
  167. package/dist/recovery.js.map +1 -0
  168. package/dist/request.d.ts +88 -0
  169. package/dist/request.d.ts.map +1 -0
  170. package/dist/request.js +422 -0
  171. package/dist/request.js.map +1 -0
  172. package/dist/run.d.ts +16 -4
  173. package/dist/run.d.ts.map +1 -1
  174. package/dist/run.js +2016 -245
  175. package/dist/run.js.map +1 -1
  176. package/dist/runs.d.ts +77 -34
  177. package/dist/runs.d.ts.map +1 -1
  178. package/dist/runs.js +267 -85
  179. package/dist/runs.js.map +1 -1
  180. package/dist/schema-to-ts.d.ts +4 -0
  181. package/dist/schema-to-ts.d.ts.map +1 -0
  182. package/dist/schema-to-ts.js +191 -0
  183. package/dist/schema-to-ts.js.map +1 -0
  184. package/dist/session.d.ts +23 -0
  185. package/dist/session.d.ts.map +1 -0
  186. package/dist/session.js +137 -0
  187. package/dist/session.js.map +1 -0
  188. package/dist/snapshot.d.ts +57 -8
  189. package/dist/snapshot.d.ts.map +1 -1
  190. package/dist/snapshot.js +1206 -109
  191. package/dist/snapshot.js.map +1 -1
  192. package/dist/steering.d.ts +75 -0
  193. package/dist/steering.d.ts.map +1 -0
  194. package/dist/steering.js +214 -0
  195. package/dist/steering.js.map +1 -0
  196. package/dist/subagents.d.ts +141 -0
  197. package/dist/subagents.d.ts.map +1 -0
  198. package/dist/subagents.js +746 -0
  199. package/dist/subagents.js.map +1 -0
  200. package/dist/tool-retry.d.ts +12 -0
  201. package/dist/tool-retry.d.ts.map +1 -0
  202. package/dist/tool-retry.js +53 -0
  203. package/dist/tool-retry.js.map +1 -0
  204. package/dist/tree.d.ts +62 -6
  205. package/dist/tree.d.ts.map +1 -1
  206. package/dist/tree.js +192 -23
  207. package/dist/tree.js.map +1 -1
  208. package/dist/types.d.ts +767 -52
  209. package/dist/types.d.ts.map +1 -1
  210. package/dist/workflow-snapshot.d.ts +8 -0
  211. package/dist/workflow-snapshot.d.ts.map +1 -0
  212. package/dist/workflow-snapshot.js +276 -0
  213. package/dist/workflow-snapshot.js.map +1 -0
  214. package/dist/workflow-types.d.ts +171 -0
  215. package/dist/workflow-types.d.ts.map +1 -0
  216. package/dist/workflow-types.js +2 -0
  217. package/dist/workflow-types.js.map +1 -0
  218. package/dist/workflow.d.ts +19 -0
  219. package/dist/workflow.d.ts.map +1 -0
  220. package/dist/workflow.js +1053 -0
  221. package/dist/workflow.js.map +1 -0
  222. package/examples/a2a-remote.ts +85 -0
  223. package/examples/a2a-server.ts +100 -0
  224. package/examples/background.ts +18 -4
  225. package/examples/code-mode.ts +76 -0
  226. package/examples/conversation.ts +57 -0
  227. package/examples/evals.ts +79 -0
  228. package/examples/guardrails.ts +56 -0
  229. package/examples/handoff.ts +79 -0
  230. package/examples/memory.ts +44 -0
  231. package/examples/otel.ts +99 -0
  232. package/examples/steering.ts +69 -0
  233. package/examples/structured-handoff.ts +92 -0
  234. package/examples/subagents.ts +127 -0
  235. package/examples/workflow.ts +74 -0
  236. package/package.json +58 -6
  237. package/src/a2a/auth.ts +62 -0
  238. package/src/a2a/client.ts +733 -0
  239. package/src/a2a/index.ts +74 -0
  240. package/src/a2a/memory-runs.ts +448 -0
  241. package/src/a2a/policy.ts +148 -0
  242. package/src/a2a/push.ts +251 -0
  243. package/src/a2a/remote.ts +1652 -0
  244. package/src/a2a/server.ts +1390 -0
  245. package/src/a2a/signing.ts +348 -0
  246. package/src/a2a/tasks.ts +260 -0
  247. package/src/a2a/wire.ts +1443 -0
  248. package/src/background-types.ts +86 -0
  249. package/src/child.ts +181 -0
  250. package/src/code-driver.ts +48 -0
  251. package/src/code-mode.ts +12 -0
  252. package/src/code-script.ts +149 -0
  253. package/src/code.ts +424 -0
  254. package/src/compaction.ts +212 -0
  255. package/src/delegation.ts +444 -155
  256. package/src/evals/driver.ts +222 -0
  257. package/src/evals/journal.ts +605 -0
  258. package/src/evals/judge.ts +188 -0
  259. package/src/evals/report.ts +295 -0
  260. package/src/evals/runner.ts +826 -0
  261. package/src/evals/scorers.ts +339 -0
  262. package/src/evals/simulation.ts +46 -0
  263. package/src/evals/testing.ts +126 -0
  264. package/src/evals/trajectory.ts +223 -0
  265. package/src/evals/types.ts +463 -0
  266. package/src/evals.ts +72 -0
  267. package/src/extensions.ts +247 -0
  268. package/src/handoff.ts +214 -0
  269. package/src/index.ts +51 -0
  270. package/src/input.ts +319 -0
  271. package/src/mcp.ts +690 -0
  272. package/src/memory-store.ts +366 -0
  273. package/src/memory.ts +893 -0
  274. package/src/otel.ts +568 -0
  275. package/src/progress.ts +214 -0
  276. package/src/quickjs.ts +524 -0
  277. package/src/recovery.ts +90 -0
  278. package/src/request.ts +513 -0
  279. package/src/run.ts +2678 -313
  280. package/src/runs.ts +464 -133
  281. package/src/schema-to-ts.ts +194 -0
  282. package/src/session.ts +178 -0
  283. package/src/snapshot.ts +1595 -124
  284. package/src/steering.ts +329 -0
  285. package/src/subagents.ts +1084 -0
  286. package/src/tool-retry.ts +86 -0
  287. package/src/tree.ts +223 -27
  288. package/src/types.ts +711 -52
  289. package/src/workflow-snapshot.ts +366 -0
  290. package/src/workflow-types.ts +213 -0
  291. package/src/workflow.ts +1316 -0
package/src/mcp.ts ADDED
@@ -0,0 +1,690 @@
1
+ // MCP servers as a source of core tools. This entry is the only file that imports the official
2
+ // SDK, an optional peer, so an app that never imports `@providerkit/agents/mcp` never loads it.
3
+ //
4
+ // The supported mode records each tool in the app: its name, the words the model reads and its
5
+ // input schema. Nothing connects until the model first calls one of them inside a run, so boot
6
+ // never waits on a sibling service, and a server that changes its list cannot change what the
7
+ // model sees. The live list is read once per connection for three checks only: the tool still
8
+ // exists, it still takes every argument the app pins, and it is still read-only when the app
9
+ // relies on that. Server text (descriptions, schemas, results, errors) is untrusted throughout.
10
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
11
+ import {
12
+ StreamableHTTPClientTransport,
13
+ StreamableHTTPError,
14
+ } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
15
+ import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.js";
16
+ import {
17
+ ErrorCode,
18
+ ListToolsResultSchema,
19
+ McpError,
20
+ ResultSchema,
21
+ type Tool as ListedTool,
22
+ } from "@modelcontextprotocol/sdk/types.js";
23
+ import {
24
+ defineTool,
25
+ ToolTimeoutError,
26
+ type JsonObjectSchema,
27
+ type Tool,
28
+ type ToolContext,
29
+ } from "@providerkit/core";
30
+
31
+ /** One tool as its server described it. `listMcpTools` returns these: save them in the app. */
32
+ export interface McpToolRecord {
33
+ /** The tool's name on the server. */
34
+ name: string;
35
+ description?: string;
36
+ inputSchema: JsonObjectSchema;
37
+ /** Only `readOnlyHint` is read. A tool without it is treated as one that can change data. */
38
+ annotations?: { readOnlyHint?: boolean };
39
+ }
40
+
41
+ /** Where the server is. Streamable HTTP only. */
42
+ export interface McpServerOptions {
43
+ /** The server's Streamable HTTP endpoint, such as `https://docs.example.com/mcp`. */
44
+ url: string;
45
+ /**
46
+ * Sent as `Authorization: Bearer <key>`, with surrounding spaces removed before sending and
47
+ * redacting. Tool metadata containing the key is refused.
48
+ */
49
+ key?: string;
50
+ /** Replaces the global fetch: a proxy, a service binding, a test. */
51
+ fetch?: (url: string | URL, init?: RequestInit) => Promise<Response>;
52
+ /** How long one call may take, connecting included, in ms. Default 60000. */
53
+ timeoutMs?: number;
54
+ }
55
+
56
+ /** What the app decides about one allowed tool. */
57
+ export interface McpToolPolicy {
58
+ /** What the model reads instead of the recorded description. */
59
+ description?: string;
60
+ /**
61
+ * Arguments the app fixes. They leave the schema the model sees and are always sent; a model
62
+ * that sends one anyway gets the call refused as invalid input.
63
+ */
64
+ pin?: Record<string, unknown>;
65
+ /**
66
+ * Ask a person before each call. A tool the server does not mark read-only must set this:
67
+ * true to ask, or false to let it run without asking.
68
+ */
69
+ needsApproval?: boolean;
70
+ /**
71
+ * Treat a tool its server marks read-only as one that can change data. There is no `true`:
72
+ * only the server's `readOnlyHint` makes a tool read-only.
73
+ */
74
+ readOnly?: false;
75
+ /** Replaces the server-wide `timeoutMs` for this tool. */
76
+ timeoutMs?: number;
77
+ }
78
+
79
+ export interface McpToolsOptions extends McpServerOptions {
80
+ /** The server's tools as `listMcpTools` returned them. */
81
+ recorded: readonly McpToolRecord[];
82
+ /** The tools the model may call, by their name on the server. No other tool reaches it. */
83
+ allow: Readonly<Record<string, McpToolPolicy>>;
84
+ /** Goes before every name with `_`: prefix "docs" turns "search" into "docs_search". */
85
+ prefix?: string;
86
+ /** Rewrites server text before the model reads it, for example to fence it as untrusted data. */
87
+ wrap?: (text: string, tool: string) => string;
88
+ }
89
+
90
+ export interface McpTools {
91
+ /** Core tools for `defineAgent`, in the order of `allow`. */
92
+ readonly tools: readonly Tool[];
93
+ /** Ends every open session. A later call connects again. */
94
+ close(): Promise<void>;
95
+ }
96
+
97
+ const DEFAULT_TIMEOUT_MS = 60_000;
98
+ // Core's own ceiling sits past ours. Our deadline fires first and says whether the call may have
99
+ // run; core's only catches a call that ignores its signal.
100
+ const BACKSTOP_MS = 1_000;
101
+ const GOODBYE_MS = 2_000;
102
+ const MAX_LIST_PAGES = 100;
103
+ // The agents SDK reserves this name for an output contract. Kept here rather than imported from
104
+ // run.ts, so this entry never loads the agent loop.
105
+ const RESULT_TOOL_NAME = "submit_result";
106
+ // Servers log this. Keep the version in step with package.json.
107
+ const CLIENT_INFO = { name: "@providerkit/agents", version: "0.2.0" };
108
+ // A runtime that refuses a header quotes the whole value in its error, key included.
109
+ const HEADER_SAFE = /^[\x20-\x7e]+$/;
110
+ // What every provider accepts: OpenAI and Anthropic allow letters, digits, _ and - up to 64, and
111
+ // Gemini also wants a letter or _ first. MCP names may hold dots and more.
112
+ const PROVIDER_NAME = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
113
+ const MEDIA_TYPE = /^[\w.+-]+\/[\w.+-]+$/;
114
+ const SAFE_AGAIN = "It changed nothing, so it is safe to call again.";
115
+ const MAYBE_RAN = "It may have run on the server, so check its effect before calling it again.";
116
+
117
+ interface Server {
118
+ url: URL;
119
+ origin: string;
120
+ key?: string;
121
+ fetch?: McpServerOptions["fetch"];
122
+ timeoutMs: number;
123
+ }
124
+
125
+ interface Plan {
126
+ /** The tool's name on the server. */
127
+ remote: string;
128
+ /** The name the model calls. */
129
+ name: string;
130
+ description: string;
131
+ inputSchema: JsonObjectSchema;
132
+ pin: Record<string, unknown>;
133
+ readOnly: boolean;
134
+ needsApproval: boolean;
135
+ timeoutMs: number;
136
+ }
137
+
138
+ /** What the live list says about one tool, read at connect. */
139
+ interface Listed {
140
+ readOnly: boolean;
141
+ takes: ReadonlySet<string>;
142
+ }
143
+
144
+ interface Live {
145
+ client: Client;
146
+ transport: StreamableHTTPClientTransport;
147
+ tools: Map<string, Listed>;
148
+ calls: number;
149
+ /** A transport failure retired it: no new call uses it, and it closes once the last one ends. */
150
+ stale: boolean;
151
+ }
152
+
153
+ /** A failure whose message we wrote or cleaned, so the model and the journal may read it. */
154
+ class McpToolError extends Error {
155
+ constructor(message: string) {
156
+ // Core's messageOf reduces a message holding <title> to that title, which would drop a host's
157
+ // fence around server text along with everything else.
158
+ super(message.replace(/<title>/gi, "&lt;title>"));
159
+ this.name = "McpToolError";
160
+ }
161
+ }
162
+
163
+ function isRecord(value: unknown): value is Record<string, unknown> {
164
+ return typeof value === "object" && value !== null && !Array.isArray(value);
165
+ }
166
+
167
+ function positive(value: unknown, label: string): number {
168
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
169
+ throw new TypeError(`${label} must be a number of milliseconds above 0.`);
170
+ return value;
171
+ }
172
+
173
+ function quoted(names: readonly string[]): string {
174
+ return names.map((name) => `"${name}"`).join(", ");
175
+ }
176
+
177
+ function readServer(options: McpServerOptions): Server {
178
+ let url: URL | undefined;
179
+ try {
180
+ url = new URL(options.url);
181
+ } catch {
182
+ url = undefined;
183
+ }
184
+ if (!url || (url.protocol !== "https:" && url.protocol !== "http:"))
185
+ throw new TypeError(
186
+ "url must be an http or https address, such as https://docs.example.com/mcp.",
187
+ );
188
+ if (
189
+ options.key !== undefined &&
190
+ (typeof options.key !== "string" || !HEADER_SAFE.test(options.key) || !options.key.trim())
191
+ )
192
+ throw new TypeError(
193
+ "The key is empty or holds a character that cannot be sent in a header (a line break or a character outside plain ASCII). Paste the key again.",
194
+ );
195
+ if (options.fetch !== undefined && typeof options.fetch !== "function")
196
+ throw new TypeError("fetch must be a function.");
197
+ return {
198
+ url,
199
+ // The origin alone names the server in messages: a path or query string can carry a token,
200
+ // and a URL can carry a user name and password.
201
+ origin: url.origin,
202
+ // Headers trims trailing spaces. Authentication and scrubbing must use the same credential.
203
+ key: options.key?.trim(),
204
+ fetch: options.fetch,
205
+ timeoutMs: positive(options.timeoutMs ?? DEFAULT_TIMEOUT_MS, "timeoutMs"),
206
+ };
207
+ }
208
+
209
+ function newClient(server: Server): { client: Client; transport: StreamableHTTPClientTransport } {
210
+ // The SDK follows a redirect only inside the same origin by default, so the key never travels
211
+ // to another host.
212
+ const transport = new StreamableHTTPClientTransport(server.url, {
213
+ ...(server.key ? { requestInit: { headers: { Authorization: `Bearer ${server.key}` } } } : {}),
214
+ ...(server.fetch ? { fetch: server.fetch } : {}),
215
+ });
216
+ return { client: new Client(CLIENT_INFO), transport };
217
+ }
218
+
219
+ // Ported from TanStack AI's listPages (packages/ai-mcp/src/list-pages.ts, MIT, Copyright (c) 2025
220
+ // Tanner Linsley): read every page, refuse a cursor that repeats and cap the page count, so a
221
+ // server cannot keep a connect busy forever. The raw request also keeps the SDK from compiling
222
+ // each tool's output schema, which this entry never uses and which is server text.
223
+ async function listAll(client: Client, options: RequestOptions): Promise<ListedTool[]> {
224
+ const tools: ListedTool[] = [];
225
+ let cursor: string | undefined;
226
+ for (let page = 0; page < MAX_LIST_PAGES; page++) {
227
+ const result = await client.request(
228
+ { method: "tools/list", ...(cursor === undefined ? {} : { params: { cursor } }) },
229
+ ListToolsResultSchema,
230
+ options,
231
+ );
232
+ tools.push(...result.tools);
233
+ if (!result.nextCursor) return tools;
234
+ if (result.nextCursor === cursor)
235
+ throw new Error("The server sent the same page of tools twice.");
236
+ cursor = result.nextCursor;
237
+ }
238
+ throw new Error(`The server listed more than ${MAX_LIST_PAGES} pages of tools.`);
239
+ }
240
+
241
+ /** Resolves when `promise` settles or after `ms`, whichever comes first. Never rejects. */
242
+ function settled(promise: Promise<unknown>, ms: number): Promise<void> {
243
+ return new Promise((resolve) => {
244
+ const timer = setTimeout(resolve, ms);
245
+ void promise
246
+ .catch(() => {})
247
+ .finally(() => {
248
+ clearTimeout(timer);
249
+ resolve();
250
+ });
251
+ });
252
+ }
253
+
254
+ async function goodbye(client: Client, transport: StreamableHTTPClientTransport): Promise<void> {
255
+ // Ending the session lets the server free it at once. A server that is down must not hold up a
256
+ // host's shutdown, so the goodbye gets two seconds before the transport closes anyway.
257
+ await settled(transport.terminateSession(), GOODBYE_MS);
258
+ await client.close().catch(() => {});
259
+ }
260
+
261
+ /** Rejects with the signal's reason when it aborts first. */
262
+ function raced<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
263
+ return new Promise((resolve, reject) => {
264
+ const stop = () => reject(signal.reason);
265
+ if (signal.aborted) {
266
+ stop();
267
+ return;
268
+ }
269
+ signal.addEventListener("abort", stop, { once: true });
270
+ void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
271
+ });
272
+ }
273
+
274
+ async function connectAndList(
275
+ client: Client,
276
+ transport: StreamableHTTPClientTransport,
277
+ timeoutMs: number,
278
+ signal?: AbortSignal,
279
+ ): Promise<ListedTool[]> {
280
+ const deadline = AbortSignal.timeout(timeoutMs);
281
+ const both = signal ? AbortSignal.any([signal, deadline]) : deadline;
282
+ const request = { timeout: timeoutMs + BACKSTOP_MS, signal: both };
283
+ try {
284
+ both.throwIfAborted();
285
+ // The SDK's request timeout does not cover notifications/initialized. Bound the entire
286
+ // handshake and every page together, and close the transport to stop a pending notification.
287
+ return await raced(
288
+ client.connect(transport, request).then(() => {
289
+ both.throwIfAborted();
290
+ return listAll(client, request);
291
+ }),
292
+ both,
293
+ );
294
+ } catch (err) {
295
+ await client.close().catch(() => {});
296
+ throw err;
297
+ }
298
+ }
299
+
300
+ function httpStatus(err: unknown): string {
301
+ return err instanceof StreamableHTTPError && typeof err.code === "number"
302
+ ? ` (HTTP ${err.code})`
303
+ : "";
304
+ }
305
+
306
+ /** A JSON-RPC error's own words: the SDK adds "MCP error <code>: " on each side of the wire. */
307
+ function serverWords(err: McpError): string {
308
+ return err.message.replace(/^(?:MCP error -?\d+: )+/, "");
309
+ }
310
+
311
+ /** The model's copy of a recorded schema, without the pinned arguments. */
312
+ function modelSchema(schema: Record<string, unknown>, pinned: readonly string[]): JsonObjectSchema {
313
+ // The dialect URI goes, as in core's zod entry: OpenAI's strict mode and Gemini reject a whole
314
+ // tool over that one key. A server can also leave out `properties`, which some providers need.
315
+ const { $schema: _dialect, ...copy } = structuredClone(schema);
316
+ const properties = isRecord(copy.properties) ? { ...copy.properties } : {};
317
+ for (const key of pinned) delete properties[key];
318
+ const required = Array.isArray(copy.required)
319
+ ? copy.required.filter((key): key is string => typeof key === "string" && !pinned.includes(key))
320
+ : undefined;
321
+ return { ...copy, type: "object", properties, ...(required ? { required } : {}) };
322
+ }
323
+
324
+ /** Reject rather than rewrite metadata: changing a name or schema can change what a call does. */
325
+ function checkMetadata(value: unknown, key: string | undefined): void {
326
+ if (!key) return;
327
+ if (typeof value === "string" && value.includes(key))
328
+ throw new McpToolError(
329
+ "The MCP tool metadata contains the server's key. Remove the key from tool names, descriptions and schemas before using these tools.",
330
+ );
331
+ if (typeof value === "object" && value !== null) {
332
+ for (const [name, item] of Object.entries(value)) {
333
+ checkMetadata(name, key);
334
+ checkMetadata(item, key);
335
+ }
336
+ }
337
+ }
338
+
339
+ function plan(options: McpToolsOptions, server: Server): Plan[] {
340
+ if (!Array.isArray(options.recorded))
341
+ throw new TypeError("recorded must be the list that listMcpTools returned.");
342
+ if (!isRecord(options.allow))
343
+ throw new TypeError("allow must name the tools the model may call, such as { search: {} }.");
344
+ if (options.prefix !== undefined && (typeof options.prefix !== "string" || !options.prefix))
345
+ throw new TypeError("prefix must be a non-empty string, such as docs.");
346
+ checkMetadata([options.recorded, Object.keys(options.allow), options.prefix], server.key);
347
+ const records = new Map<string, McpToolRecord>();
348
+ for (const record of options.recorded) {
349
+ // Records usually come from a saved JSON file, which no compiler checked.
350
+ if (typeof record?.name !== "string")
351
+ throw new TypeError("Every recorded tool needs a name. Record the server's tools again.");
352
+ if (records.has(record.name))
353
+ throw new TypeError(`The recorded tools hold "${record.name}" twice. Record them again.`);
354
+ records.set(record.name, record);
355
+ }
356
+ const names = new Map<string, string>();
357
+ return Object.entries(options.allow).map(([remote, policy]) => {
358
+ const record = records.get(remote);
359
+ if (!record)
360
+ throw new TypeError(
361
+ `"${remote}" is in allow but not in the recorded tools. Record the server's tools again with listMcpTools, or remove it from allow.`,
362
+ );
363
+ if (!isRecord(policy)) throw new TypeError(`allow.${remote} must be an object, such as {}.`);
364
+ const schema: unknown = record.inputSchema;
365
+ if (!isRecord(schema) || schema.type !== "object")
366
+ throw new TypeError(`The recorded inputSchema of "${remote}" is not a JSON object schema.`);
367
+ const takes = isRecord(schema.properties) ? schema.properties : {};
368
+
369
+ const pin = policy.pin === undefined ? {} : policy.pin;
370
+ if (!isRecord(pin)) throw new TypeError(`allow.${remote}.pin must be an object of arguments.`);
371
+ checkMetadata(Object.keys(pin), server.key);
372
+ const unknown = Object.keys(pin).filter((key) => !Object.hasOwn(takes, key));
373
+ // A typo here would leave the real argument in the model's hands while the app believes it
374
+ // is fixed, so a pin must name an argument the recorded schema declares.
375
+ if (unknown.length)
376
+ throw new TypeError(
377
+ `allow.${remote}.pin sets ${quoted(unknown)}, which "${remote}" does not take. Check the names against its recorded inputSchema.`,
378
+ );
379
+
380
+ if (policy.readOnly !== undefined && policy.readOnly !== false)
381
+ throw new TypeError(
382
+ `allow.${remote}.readOnly can only be false. Whether "${remote}" is read-only comes from the server's readOnlyHint.`,
383
+ );
384
+ // Only the server's own hint makes a tool read-only. The host can take that away, never add it.
385
+ const readOnly = record.annotations?.readOnlyHint === true && policy.readOnly !== false;
386
+ if (policy.needsApproval !== undefined && typeof policy.needsApproval !== "boolean")
387
+ throw new TypeError(`allow.${remote}.needsApproval must be true or false.`);
388
+ if (!readOnly && policy.needsApproval === undefined)
389
+ throw new TypeError(
390
+ `"${remote}" may change data on the server. Set needsApproval: true to ask a person before each call, or needsApproval: false to let it run without asking.`,
391
+ );
392
+
393
+ const description = policy.description ?? record.description ?? "";
394
+ if (typeof description !== "string")
395
+ throw new TypeError(`allow.${remote}.description must be a string.`);
396
+
397
+ const name = (options.prefix ? `${options.prefix}_${remote}` : remote).replace(
398
+ /[^A-Za-z0-9_-]/g,
399
+ "_",
400
+ );
401
+ checkMetadata([name, description], server.key);
402
+ if (!PROVIDER_NAME.test(name))
403
+ throw new TypeError(
404
+ `"${name}" cannot be a tool name: providers accept up to 64 letters, digits, _ and -, starting with a letter or _. Set a shorter prefix, or one that starts with a letter.`,
405
+ );
406
+ if (name === RESULT_TOOL_NAME)
407
+ throw new TypeError(
408
+ `"${RESULT_TOOL_NAME}" is reserved by @providerkit/agents for an agent's result. Set a prefix.`,
409
+ );
410
+ const clash = names.get(name);
411
+ if (clash !== undefined)
412
+ throw new TypeError(
413
+ `"${clash}" and "${remote}" would both reach the model as "${name}". Allow only one of them.`,
414
+ );
415
+ names.set(name, remote);
416
+
417
+ return {
418
+ remote,
419
+ name,
420
+ description,
421
+ inputSchema: modelSchema(schema, Object.keys(pin)),
422
+ pin: structuredClone(pin),
423
+ readOnly,
424
+ needsApproval: policy.needsApproval ?? false,
425
+ timeoutMs: positive(policy.timeoutMs ?? server.timeoutMs, `allow.${remote}.timeoutMs`),
426
+ };
427
+ });
428
+ }
429
+
430
+ /** Why a call must not go out, judged against the list the server sent at connect. */
431
+ function refusal(plan: Plan, listed: Listed | undefined): string | undefined {
432
+ if (!listed)
433
+ return `${plan.name} did not run: the server no longer has a tool named "${plan.remote}".`;
434
+ if (plan.readOnly && !listed.readOnly)
435
+ return `${plan.name} did not run: the server no longer marks "${plan.remote}" read-only, and this app allowed it only as a read-only tool.`;
436
+ // A pinned argument usually scopes the call. If the server renamed it, sending the call would
437
+ // drop that scope without anyone noticing.
438
+ const dropped = Object.keys(plan.pin).filter((key) => !listed.takes.has(key));
439
+ if (dropped.length)
440
+ return `${plan.name} did not run: "${plan.remote}" on the server no longer takes ${quoted(dropped)}, which this app sets.`;
441
+ return undefined;
442
+ }
443
+
444
+ /** A call result as text. Read loosely, so a content type newer than this SDK still shows up. */
445
+ function textOf(result: Record<string, unknown>): string {
446
+ const content = Array.isArray(result.content) ? result.content : [];
447
+ if (content.length === 0 && result.structuredContent !== undefined)
448
+ return JSON.stringify(result.structuredContent) ?? "";
449
+ return content.map(partText).join("\n");
450
+ }
451
+
452
+ const PART_WORDS: Record<string, string> = {
453
+ image: "image",
454
+ audio: "audio",
455
+ resource_link: "link",
456
+ resource: "file",
457
+ };
458
+
459
+ function partText(part: unknown): string {
460
+ if (!isRecord(part)) return "[content not shown]";
461
+ if (part.type === "text" && typeof part.text === "string") return part.text;
462
+ const resource = isRecord(part.resource) ? part.resource : undefined;
463
+ if (part.type === "resource" && typeof resource?.text === "string") return resource.text;
464
+ // Something that cannot be shown still says it was there: a model told nothing assumes nothing
465
+ // came back.
466
+ const word = (typeof part.type === "string" && PART_WORDS[part.type]) || "content";
467
+ const media = resource ? resource.mimeType : part.mimeType;
468
+ return typeof media === "string" && MEDIA_TYPE.test(media)
469
+ ? `[${word} not shown: ${media}]`
470
+ : `[${word} not shown]`;
471
+ }
472
+
473
+ /**
474
+ * Lists a server's tools once, so a developer can save them in the app and pass them to
475
+ * `mcpTools` as `recorded`. Run it when you add a server or want to take its changes.
476
+ */
477
+ export async function listMcpTools(
478
+ options: McpServerOptions & { signal?: AbortSignal },
479
+ ): Promise<McpToolRecord[]> {
480
+ const server = readServer(options);
481
+ const { client, transport } = newClient(server);
482
+ const scrub = scrubber(server.key);
483
+ try {
484
+ const listed = await connectAndList(client, transport, server.timeoutMs, options.signal);
485
+ const records = listed.map((tool): McpToolRecord => ({
486
+ name: tool.name,
487
+ ...(tool.description === undefined ? {} : { description: tool.description }),
488
+ inputSchema: tool.inputSchema,
489
+ ...(tool.annotations?.readOnlyHint === undefined
490
+ ? {}
491
+ : { annotations: { readOnlyHint: tool.annotations.readOnlyHint } }),
492
+ }));
493
+ checkMetadata(records, server.key);
494
+ return records;
495
+ } catch (err) {
496
+ if (options.signal?.aborted) throw options.signal.reason;
497
+ if (err instanceof McpToolError) throw err;
498
+ const said =
499
+ err instanceof McpError && err.code !== ErrorCode.ConnectionClosed
500
+ ? scrub(serverWords(err))
501
+ : "";
502
+ throw new Error(
503
+ `Could not list the tools of the MCP server at ${server.origin}${httpStatus(err)}.${said ? ` The server said: ${said}` : ""}`,
504
+ );
505
+ } finally {
506
+ await goodbye(client, transport);
507
+ }
508
+ }
509
+
510
+ function scrubber(key: string | undefined): (text: string) => string {
511
+ // A server can echo the request back, headers included.
512
+ return key ? (text) => text.replaceAll(key, "[key removed]") : (text) => text;
513
+ }
514
+
515
+ /**
516
+ * Core tools for the tools an app allows on one MCP server. Building them does no I/O; the first
517
+ * call connects, and a call after a failure or `close()` connects again.
518
+ */
519
+ export function mcpTools(options: McpToolsOptions): McpTools {
520
+ const server = readServer(options);
521
+ const plans = plan(options, server);
522
+ if (options.wrap !== undefined && typeof options.wrap !== "function")
523
+ throw new TypeError("wrap must be a function that returns the text the model reads.");
524
+ const wrap = options.wrap ?? ((text: string) => text);
525
+ const scrub = scrubber(server.key);
526
+
527
+ let current: Promise<Live> | undefined;
528
+ const open = new Set<Live>();
529
+
530
+ async function shut(live: Live): Promise<void> {
531
+ if (!open.delete(live)) return;
532
+ await goodbye(live.client, live.transport);
533
+ }
534
+
535
+ // One connection serves every tool of this server. It is not tied to any one call's signal: a
536
+ // call that gives up stops waiting, and the connection stays for the next one.
537
+ function connect(): Promise<Live> {
538
+ const live: Live = { ...newClient(server), tools: new Map(), calls: 0, stale: false };
539
+ open.add(live);
540
+ const pending = (async () => {
541
+ for (const tool of await connectAndList(live.client, live.transport, server.timeoutMs)) {
542
+ live.tools.set(tool.name, {
543
+ readOnly: tool.annotations?.readOnlyHint === true,
544
+ takes: new Set(Object.keys(tool.inputSchema.properties ?? {})),
545
+ });
546
+ }
547
+ return live;
548
+ })();
549
+ // A failed connect is not kept: the next call tries again.
550
+ pending.catch(() => {
551
+ if (current === pending) current = undefined;
552
+ void shut(live);
553
+ });
554
+ return pending;
555
+ }
556
+
557
+ async function acquire(pending: Promise<Live>, signal: AbortSignal) {
558
+ const live = await raced(pending, signal);
559
+ live.calls++;
560
+ return {
561
+ live,
562
+ retire() {
563
+ live.stale = true;
564
+ if (current === pending) current = undefined;
565
+ },
566
+ release() {
567
+ live.calls--;
568
+ if (live.stale && live.calls === 0) void shut(live);
569
+ },
570
+ };
571
+ }
572
+
573
+ function timedOut(plan: Plan, sent: boolean, ms = plan.timeoutMs): ToolTimeoutError {
574
+ const error = new ToolTimeoutError(plan.name, ms);
575
+ error.message = sent
576
+ ? `${plan.name} timed out after ${ms} ms. ${plan.readOnly ? SAFE_AGAIN : MAYBE_RAN}`
577
+ : `${plan.name} did not run: connecting to the MCP server at ${server.origin} took longer than ${ms} ms.`;
578
+ return error;
579
+ }
580
+
581
+ /** The call went out and no answer came back, so only a refusal proves it did not run. */
582
+ function lost(plan: Plan, err: unknown): string {
583
+ const status = err instanceof StreamableHTTPError ? err.code : undefined;
584
+ // Streamable HTTP answers a request it ran with 200. A 4xx is the transport turning it away
585
+ // first: a session the server forgot after a restart, a refused key, a full queue.
586
+ if (typeof status === "number" && status >= 400 && status < 500)
587
+ return `${plan.name} did not run: the MCP server at ${server.origin} refused the request (HTTP ${status}).`;
588
+ return `The connection to the MCP server at ${server.origin} failed before ${plan.name} returned${httpStatus(err)}. ${plan.readOnly ? SAFE_AGAIN : MAYBE_RAN}`;
589
+ }
590
+
591
+ function build(plan: Plan): Tool<Record<string, unknown>, string> {
592
+ const pinned = Object.keys(plan.pin);
593
+
594
+ function validate(raw: unknown): Record<string, unknown> {
595
+ const args = raw === undefined || raw === null ? {} : raw;
596
+ if (!isRecord(args)) throw new Error("send the arguments as one JSON object.");
597
+ const sent = pinned.filter((key) => Object.hasOwn(args, key));
598
+ // The model never saw these keys, so sending one is a guess or an injection. Refusing it
599
+ // shows the attempt; quietly overwriting it would hide it.
600
+ if (sent.length)
601
+ throw new Error(
602
+ `do not send ${quoted(sent)}. The app sets ${sent.length === 1 ? "it" : "them"}.`,
603
+ );
604
+ return args;
605
+ }
606
+
607
+ async function run(args: Record<string, unknown>, ctx: ToolContext): Promise<string> {
608
+ // Core's typed call skips validate. Check both paths, and inject pins only here so invoke's
609
+ // validated input does not look like an override when it reaches this boundary.
610
+ const input = { ...validate(args), ...structuredClone(plan.pin) };
611
+ // Core hands every run its own signal: the caller's abort and core's ceiling, bridged.
612
+ const signal = ctx.signal ?? new AbortController().signal;
613
+ let deadline: AbortSignal | undefined;
614
+ let sent = false;
615
+ let lease: Awaited<ReturnType<typeof acquire>> | undefined;
616
+ let result: Record<string, unknown>;
617
+ // Only the connection and the request sit in this try, so a host's wrap that throws is
618
+ // reported as its own failure, never as a lost connection.
619
+ try {
620
+ // Start the connection's clock first. With equal budgets it must retire before this
621
+ // call's deadline lets the next caller reuse the still-pending connection.
622
+ const pending = (current ??= connect());
623
+ deadline = AbortSignal.timeout(plan.timeoutMs);
624
+ const both = AbortSignal.any([signal, deadline]);
625
+ lease = await acquire(pending, both);
626
+ const why = refusal(plan, lease.live.tools.get(plan.remote));
627
+ if (why) throw new McpToolError(why);
628
+ sent = true;
629
+ result = await lease.live.client.request(
630
+ { method: "tools/call", params: { name: plan.remote, arguments: input } },
631
+ ResultSchema,
632
+ // The SDK's own clock gets the backstop too, so our deadline is the one that speaks.
633
+ { signal: both, timeout: plan.timeoutMs + BACKSTOP_MS },
634
+ );
635
+ } catch (err) {
636
+ // The caller's abort, or core's ceiling, leaves untouched: core reports it as such.
637
+ if (signal.aborted) throw signal.reason;
638
+ if (err instanceof McpToolError) throw err;
639
+ // Never sent again from here, by this entry or after a reconnect: a call that may have
640
+ // changed data is the model's to check, with the words below.
641
+ if (deadline?.aborted) throw timedOut(plan, sent);
642
+ if (!sent && err instanceof DOMException && err.name === "TimeoutError")
643
+ throw timedOut(plan, false, server.timeoutMs);
644
+ // A failed connect is never the server's words: only the status names what went wrong.
645
+ if (!sent)
646
+ throw new McpToolError(
647
+ `${plan.name} did not run: connecting to the MCP server at ${server.origin} failed${httpStatus(err)}.`,
648
+ );
649
+ // The server answered with a JSON-RPC error. The connection is fine.
650
+ if (err instanceof McpError && err.code !== ErrorCode.ConnectionClosed) {
651
+ const said = scrub(serverWords(err));
652
+ throw new McpToolError(
653
+ said ? wrap(said, plan.name) : `${plan.name} failed and the server gave no reason.`,
654
+ );
655
+ }
656
+ lease?.retire();
657
+ throw new McpToolError(lost(plan, err));
658
+ } finally {
659
+ lease?.release();
660
+ }
661
+ const text = scrub(textOf(result));
662
+ if (result.isError === true)
663
+ throw new McpToolError(
664
+ text ? wrap(text, plan.name) : `${plan.name} failed and the server gave no reason.`,
665
+ );
666
+ return text ? wrap(text, plan.name) : `${plan.name} finished and returned no content.`;
667
+ }
668
+
669
+ return defineTool<Record<string, unknown>, string>({
670
+ name: plan.name,
671
+ description: plan.description,
672
+ inputSchema: plan.inputSchema,
673
+ validate,
674
+ run,
675
+ summarize: (text) => text,
676
+ timeoutMs: plan.timeoutMs + BACKSTOP_MS,
677
+ isReadOnly: plan.readOnly,
678
+ needsApproval: plan.needsApproval,
679
+ isConcurrencySafe: plan.readOnly,
680
+ });
681
+ }
682
+
683
+ return {
684
+ tools: plans.map(build),
685
+ async close() {
686
+ current = undefined;
687
+ await Promise.all([...open].map(shut));
688
+ },
689
+ };
690
+ }