agentfootprint 7.11.0 → 7.13.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 (141) hide show
  1. package/dist/core/Agent.js +52 -7
  2. package/dist/core/Agent.js.map +1 -1
  3. package/dist/core/agent/AgentBuilder.js +59 -1
  4. package/dist/core/agent/AgentBuilder.js.map +1 -1
  5. package/dist/core/agent/buildAgentChart.js +6 -0
  6. package/dist/core/agent/buildAgentChart.js.map +1 -1
  7. package/dist/core/agent/buildDynamicAgentChart.js +14 -0
  8. package/dist/core/agent/buildDynamicAgentChart.js.map +1 -1
  9. package/dist/core/agent/stages/callLLM.js +10 -4
  10. package/dist/core/agent/stages/callLLM.js.map +1 -1
  11. package/dist/core/agent/stages/seed.js +16 -0
  12. package/dist/core/agent/stages/seed.js.map +1 -1
  13. package/dist/core/slots/buildSystemPromptSlot.js +2 -1
  14. package/dist/core/slots/buildSystemPromptSlot.js.map +1 -1
  15. package/dist/debug.js +5 -2
  16. package/dist/debug.js.map +1 -1
  17. package/dist/esm/core/Agent.d.ts +11 -3
  18. package/dist/esm/core/Agent.js +52 -7
  19. package/dist/esm/core/Agent.js.map +1 -1
  20. package/dist/esm/core/agent/AgentBuilder.d.ts +48 -1
  21. package/dist/esm/core/agent/AgentBuilder.js +59 -1
  22. package/dist/esm/core/agent/AgentBuilder.js.map +1 -1
  23. package/dist/esm/core/agent/buildAgentChart.js +6 -0
  24. package/dist/esm/core/agent/buildAgentChart.js.map +1 -1
  25. package/dist/esm/core/agent/buildDynamicAgentChart.js +14 -0
  26. package/dist/esm/core/agent/buildDynamicAgentChart.js.map +1 -1
  27. package/dist/esm/core/agent/stages/callLLM.d.ts +9 -0
  28. package/dist/esm/core/agent/stages/callLLM.js +10 -4
  29. package/dist/esm/core/agent/stages/callLLM.js.map +1 -1
  30. package/dist/esm/core/agent/stages/seed.d.ts +10 -1
  31. package/dist/esm/core/agent/stages/seed.js +16 -0
  32. package/dist/esm/core/agent/stages/seed.js.map +1 -1
  33. package/dist/esm/core/agent/types.d.ts +69 -1
  34. package/dist/esm/core/slots/buildSystemPromptSlot.d.ts +19 -4
  35. package/dist/esm/core/slots/buildSystemPromptSlot.js +2 -1
  36. package/dist/esm/core/slots/buildSystemPromptSlot.js.map +1 -1
  37. package/dist/esm/debug.d.ts +2 -2
  38. package/dist/esm/debug.js +2 -2
  39. package/dist/esm/debug.js.map +1 -1
  40. package/dist/esm/index.d.ts +1 -0
  41. package/dist/esm/index.js.map +1 -1
  42. package/dist/esm/lib/context-bisect/index.d.ts +3 -1
  43. package/dist/esm/lib/context-bisect/index.js +5 -0
  44. package/dist/esm/lib/context-bisect/index.js.map +1 -1
  45. package/dist/esm/lib/context-bisect/trajectory.d.ts +8 -0
  46. package/dist/esm/lib/context-bisect/trajectory.js +10 -3
  47. package/dist/esm/lib/context-bisect/trajectory.js.map +1 -1
  48. package/dist/esm/lib/context-bisect/variable-recall.d.ts +171 -0
  49. package/dist/esm/lib/context-bisect/variable-recall.js +0 -0
  50. package/dist/esm/lib/context-bisect/variable-recall.js.map +1 -0
  51. package/dist/esm/lib/context-bisect/variableToBacktrackTrace.d.ts +53 -0
  52. package/dist/esm/lib/context-bisect/variableToBacktrackTrace.js +142 -0
  53. package/dist/esm/lib/context-bisect/variableToBacktrackTrace.js.map +1 -0
  54. package/dist/esm/lib/context-bisect/walk-to-root.d.ts +37 -2
  55. package/dist/esm/lib/context-bisect/walk-to-root.js +61 -6
  56. package/dist/esm/lib/context-bisect/walk-to-root.js.map +1 -1
  57. package/dist/esm/lib/injection-engine/index.d.ts +1 -0
  58. package/dist/esm/lib/injection-engine/index.js +4 -0
  59. package/dist/esm/lib/injection-engine/index.js.map +1 -1
  60. package/dist/esm/lib/injection-engine/skillsFromDir.d.ts +80 -0
  61. package/dist/esm/lib/injection-engine/skillsFromDir.js +243 -0
  62. package/dist/esm/lib/injection-engine/skillsFromDir.js.map +1 -0
  63. package/dist/esm/lib/mcp/index.d.ts +6 -5
  64. package/dist/esm/lib/mcp/index.js +5 -4
  65. package/dist/esm/lib/mcp/index.js.map +1 -1
  66. package/dist/esm/lib/mcp/mcpClient.js +21 -9
  67. package/dist/esm/lib/mcp/mcpClient.js.map +1 -1
  68. package/dist/esm/lib/mcp/mcpServe.d.ts +70 -0
  69. package/dist/esm/lib/mcp/mcpServe.js +374 -0
  70. package/dist/esm/lib/mcp/mcpServe.js.map +1 -0
  71. package/dist/esm/lib/mcp/types.d.ts +130 -17
  72. package/dist/esm/lib/mcp/types.js +10 -10
  73. package/dist/esm/tool-providers/index.d.ts +8 -2
  74. package/dist/esm/tool-providers/index.js +7 -1
  75. package/dist/esm/tool-providers/index.js.map +1 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/lib/context-bisect/index.js +9 -1
  78. package/dist/lib/context-bisect/index.js.map +1 -1
  79. package/dist/lib/context-bisect/trajectory.js +10 -3
  80. package/dist/lib/context-bisect/trajectory.js.map +1 -1
  81. package/dist/lib/context-bisect/variable-recall.js +0 -0
  82. package/dist/lib/context-bisect/variable-recall.js.map +1 -0
  83. package/dist/lib/context-bisect/variableToBacktrackTrace.js +146 -0
  84. package/dist/lib/context-bisect/variableToBacktrackTrace.js.map +1 -0
  85. package/dist/lib/context-bisect/walk-to-root.js +61 -6
  86. package/dist/lib/context-bisect/walk-to-root.js.map +1 -1
  87. package/dist/lib/injection-engine/index.js +6 -1
  88. package/dist/lib/injection-engine/index.js.map +1 -1
  89. package/dist/lib/injection-engine/skillsFromDir.js +270 -0
  90. package/dist/lib/injection-engine/skillsFromDir.js.map +1 -0
  91. package/dist/lib/mcp/index.js +7 -5
  92. package/dist/lib/mcp/index.js.map +1 -1
  93. package/dist/lib/mcp/mcpClient.js +21 -9
  94. package/dist/lib/mcp/mcpClient.js.map +1 -1
  95. package/dist/lib/mcp/mcpServe.js +401 -0
  96. package/dist/lib/mcp/mcpServe.js.map +1 -0
  97. package/dist/lib/mcp/types.js +10 -10
  98. package/dist/tool-providers/index.js +8 -1
  99. package/dist/tool-providers/index.js.map +1 -1
  100. package/dist/types/core/Agent.d.ts +11 -3
  101. package/dist/types/core/Agent.d.ts.map +1 -1
  102. package/dist/types/core/agent/AgentBuilder.d.ts +48 -1
  103. package/dist/types/core/agent/AgentBuilder.d.ts.map +1 -1
  104. package/dist/types/core/agent/buildAgentChart.d.ts.map +1 -1
  105. package/dist/types/core/agent/buildDynamicAgentChart.d.ts.map +1 -1
  106. package/dist/types/core/agent/stages/callLLM.d.ts +9 -0
  107. package/dist/types/core/agent/stages/callLLM.d.ts.map +1 -1
  108. package/dist/types/core/agent/stages/seed.d.ts +10 -1
  109. package/dist/types/core/agent/stages/seed.d.ts.map +1 -1
  110. package/dist/types/core/agent/types.d.ts +69 -1
  111. package/dist/types/core/agent/types.d.ts.map +1 -1
  112. package/dist/types/core/slots/buildSystemPromptSlot.d.ts +19 -4
  113. package/dist/types/core/slots/buildSystemPromptSlot.d.ts.map +1 -1
  114. package/dist/types/debug.d.ts +2 -2
  115. package/dist/types/debug.d.ts.map +1 -1
  116. package/dist/types/index.d.ts +1 -0
  117. package/dist/types/index.d.ts.map +1 -1
  118. package/dist/types/lib/context-bisect/index.d.ts +3 -1
  119. package/dist/types/lib/context-bisect/index.d.ts.map +1 -1
  120. package/dist/types/lib/context-bisect/trajectory.d.ts +8 -0
  121. package/dist/types/lib/context-bisect/trajectory.d.ts.map +1 -1
  122. package/dist/types/lib/context-bisect/variable-recall.d.ts +172 -0
  123. package/dist/types/lib/context-bisect/variable-recall.d.ts.map +1 -0
  124. package/dist/types/lib/context-bisect/variableToBacktrackTrace.d.ts +54 -0
  125. package/dist/types/lib/context-bisect/variableToBacktrackTrace.d.ts.map +1 -0
  126. package/dist/types/lib/context-bisect/walk-to-root.d.ts +37 -2
  127. package/dist/types/lib/context-bisect/walk-to-root.d.ts.map +1 -1
  128. package/dist/types/lib/injection-engine/index.d.ts +1 -0
  129. package/dist/types/lib/injection-engine/index.d.ts.map +1 -1
  130. package/dist/types/lib/injection-engine/skillsFromDir.d.ts +81 -0
  131. package/dist/types/lib/injection-engine/skillsFromDir.d.ts.map +1 -0
  132. package/dist/types/lib/mcp/index.d.ts +6 -5
  133. package/dist/types/lib/mcp/index.d.ts.map +1 -1
  134. package/dist/types/lib/mcp/mcpClient.d.ts.map +1 -1
  135. package/dist/types/lib/mcp/mcpServe.d.ts +71 -0
  136. package/dist/types/lib/mcp/mcpServe.d.ts.map +1 -0
  137. package/dist/types/lib/mcp/types.d.ts +130 -17
  138. package/dist/types/lib/mcp/types.d.ts.map +1 -1
  139. package/dist/types/tool-providers/index.d.ts +8 -2
  140. package/dist/types/tool-providers/index.d.ts.map +1 -1
  141. package/package.json +4 -3
@@ -0,0 +1,401 @@
1
+ "use strict";
2
+ /**
3
+ * mcpServe — expose your agentfootprint tools AS an MCP server.
4
+ *
5
+ * const handle = await mcpServe([lookupTool, refundTool], {
6
+ * name: 'support-desk',
7
+ * version: '1.0.0',
8
+ * });
9
+ *
10
+ * // …later
11
+ * await handle.close();
12
+ *
13
+ * `mcpClient` pulls someone else's tools in. This pushes yours out, so
14
+ * the tool you already wrote, tested and governed can be called by any
15
+ * MCP client — a desktop host, another team's agent, an IDE — without
16
+ * being rewritten against a second tool interface.
17
+ *
18
+ * Pattern: Adapter (GoF), pointed the other way. `mcpClient` translates
19
+ * MCP → `Tool`; this translates `Tool` → MCP. Same SDK, same
20
+ * lazy-require discipline, mirrored lifecycle (`close()`).
21
+ *
22
+ * ── The one promise worth stating plainly ────────────────────────────
23
+ * A served tool is THE SAME OBJECT you passed in. `mcpServe` holds your
24
+ * `Tool` by reference and calls `tool.execute(args, ctx)` — it never
25
+ * copies the schema and re-implements the body, never unwraps a
26
+ * decorator, never reaches past a wrapper to an inner tool. So whatever
27
+ * governance you composed around that tool — a permission check inside
28
+ * `execute`, a redaction step, an audit hook — is still the thing that
29
+ * runs when a remote client calls it. Serving is not a second door into
30
+ * your tool; it is the same door with a longer corridor.
31
+ *
32
+ * Two demands the library CANNOT keep over MCP are refused at
33
+ * construction rather than silently dropped:
34
+ * - `checkIn` (human consent before the tool runs) needs a pause
35
+ * channel that a request/response protocol does not have.
36
+ * - `needs` (declare-and-push credentials) needs a provider; without
37
+ * one the tool would run with `ctx.credential` undefined.
38
+ *
39
+ * ── Schemas ──────────────────────────────────────────────────────────
40
+ * Tools already carry JSON Schema in `schema.inputSchema`, and MCP's
41
+ * `tools/list` wants JSON Schema, so the mapping is the identity
42
+ * function. That is also why this builds on the SDK's low-level
43
+ * `Server` rather than its `McpServer` convenience wrapper — the latter
44
+ * takes zod schemas, which would mean converting a JSON Schema you
45
+ * already have into zod (a new dependency) to convert it straight back.
46
+ */
47
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
48
+ if (k2 === undefined) k2 = k;
49
+ var desc = Object.getOwnPropertyDescriptor(m, k);
50
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
51
+ desc = { enumerable: true, get: function() { return m[k]; } };
52
+ }
53
+ Object.defineProperty(o, k2, desc);
54
+ }) : (function(o, m, k, k2) {
55
+ if (k2 === undefined) k2 = k;
56
+ o[k2] = m[k];
57
+ }));
58
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
59
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
60
+ }) : function(o, v) {
61
+ o["default"] = v;
62
+ });
63
+ var __importStar = (this && this.__importStar) || function (mod) {
64
+ if (mod && mod.__esModule) return mod;
65
+ var result = {};
66
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
67
+ __setModuleDefault(result, mod);
68
+ return result;
69
+ };
70
+ Object.defineProperty(exports, "__esModule", { value: true });
71
+ exports.CALL_TOOL_SENTINEL = exports.LIST_TOOLS_SENTINEL = exports.mcpServe = void 0;
72
+ const types_js_1 = require("../../identity/types.js");
73
+ const lazyRequire_js_1 = require("../lazyRequire.js");
74
+ const DEFAULT_SERVER_NAME = 'agentfootprint';
75
+ const DEFAULT_SERVER_VERSION = '0.0.0';
76
+ const DEFAULT_HTTP_PATH = '/mcp';
77
+ /**
78
+ * Serve `tools` over MCP. Resolves once the transport is connected (for
79
+ * `http`, once the socket is listening), so holding the handle means the
80
+ * server is live.
81
+ *
82
+ * @throws at construction when `tools` is empty, when two tools share a
83
+ * name, when a tool declares `checkIn`, or when a tool declares `needs`
84
+ * without `opts.credentials` — see the module header. Also throws when
85
+ * `@modelcontextprotocol/sdk` is not installed.
86
+ */
87
+ async function mcpServe(tools, opts = {}) {
88
+ const name = opts.name ?? DEFAULT_SERVER_NAME;
89
+ const version = opts.version ?? DEFAULT_SERVER_VERSION;
90
+ const byName = validateServableTools(tools, name, opts.credentials);
91
+ const credentials = opts.credentials ?? (0, types_js_1.unconfiguredCredentialProvider)();
92
+ const listing = tools.map((t) => ({
93
+ name: t.schema.name,
94
+ ...(t.schema.description !== undefined && { description: t.schema.description }),
95
+ inputSchema: t.schema.inputSchema ?? { type: 'object', properties: {} },
96
+ }));
97
+ // Order matters: the server is resolved FIRST so that a missing SDK is
98
+ // reported by the message that tells you how to install it, rather than
99
+ // by the narrower one about a single submodule.
100
+ const rootServer = opts._server ?? (await resolveServer(name, version));
101
+ const { listSchema, callSchema } = await resolveRequestSchemas(opts._server !== undefined);
102
+ let callCounter = 0;
103
+ const handleCall = async (request, extra) => {
104
+ // Everything below this line is inside one try/catch on purpose. A
105
+ // client we do not control chose this request; a bad choice is a tool
106
+ // error reported back over the protocol, never an exception that
107
+ // escapes the SDK's dispatch loop and takes the server down with it.
108
+ try {
109
+ const toolName = request?.params?.name;
110
+ const tool = typeof toolName === 'string' ? byName.get(toolName) : undefined;
111
+ if (!tool) {
112
+ return toolError(`Unknown tool '${String(toolName)}'. Served tools: ${listing
113
+ .map((t) => t.name)
114
+ .join(', ')}.`);
115
+ }
116
+ const ctx = await buildExecutionContext(tool, `mcp-${name}-${++callCounter}`, {
117
+ credentials,
118
+ hasCredentials: opts.credentials !== undefined,
119
+ ...(extra?.signal && { signal: extra.signal }),
120
+ });
121
+ if ('blocked' in ctx)
122
+ return toolError(ctx.blocked);
123
+ // Args are forwarded EXACTLY as the client sent them. Validating
124
+ // them here would mean a second, weaker copy of the tool's own
125
+ // contract — and a tool that already rejects bad input is the one
126
+ // place that rejection belongs.
127
+ const result = await tool.execute(request?.params?.arguments, ctx.context);
128
+ return { content: [{ type: 'text', text: stringifyResult(result) }] };
129
+ }
130
+ catch (error) {
131
+ return toolError(error instanceof Error ? error.message : String(error));
132
+ }
133
+ };
134
+ /**
135
+ * Put our two handlers on one SDK server. Factored out of the body
136
+ * because the streamable-HTTP path cannot reuse a single server: the
137
+ * SDK's stateless transport refuses a second request ("Stateless
138
+ * transport cannot be reused across requests"), so that path builds a
139
+ * fresh server + transport per request and needs to install the same
140
+ * two handlers on each one. `listing` and `byName` are captured, so
141
+ * every server instance serves the same tools — the same objects.
142
+ */
143
+ const install = (server) => {
144
+ server.setRequestHandler(listSchema, () => ({ tools: listing }));
145
+ server.setRequestHandler(callSchema, handleCall);
146
+ return server;
147
+ };
148
+ const sdk = install(rootServer);
149
+ const connection = await connectTransport(sdk, opts.transport ?? { transport: 'stdio' }, opts, async () => install(await resolveServer(name, version)));
150
+ let closed = false;
151
+ return {
152
+ name,
153
+ toolNames: listing.map((t) => t.name),
154
+ async close() {
155
+ if (closed)
156
+ return;
157
+ closed = true;
158
+ await connection.close();
159
+ await sdk.close();
160
+ },
161
+ };
162
+ }
163
+ exports.mcpServe = mcpServe;
164
+ // ─── Construction-time refusals ────────────────────────────────────
165
+ /**
166
+ * Build the dispatch map and refuse, by name, every tool this transport
167
+ * cannot honour. All of these are author mistakes, and all of them are
168
+ * invisible at run time if we let them through — a duplicate name means
169
+ * one tool silently shadows another; a dropped `checkIn` means a
170
+ * consent gate that quietly stopped gating.
171
+ */
172
+ function validateServableTools(tools, serverName, credentials) {
173
+ if (tools.length === 0) {
174
+ throw new Error(`mcpServe('${serverName}'): no tools to serve. Pass at least one Tool — a server ` +
175
+ `advertising an empty tool list is indistinguishable from a broken one.`);
176
+ }
177
+ const byName = new Map();
178
+ for (const tool of tools) {
179
+ const name = tool.schema.name;
180
+ if (byName.has(name)) {
181
+ throw new Error(`mcpServe('${serverName}'): duplicate tool name '${name}'. MCP clients dispatch by ` +
182
+ `name, so one of the two could never be reached.`);
183
+ }
184
+ if (tool.checkIn !== undefined) {
185
+ throw new Error(`mcpServe('${serverName}'): tool '${name}' declares checkIn, which asks a human to ` +
186
+ `approve the call before it runs. MCP is request/response — there is no pause to ` +
187
+ `carry that ask — so serving it would drop the consent gate silently. Serve a ` +
188
+ `variant without checkIn, or keep this tool inside an agent that can pause.`);
189
+ }
190
+ if (tool.needs !== undefined && credentials === undefined) {
191
+ throw new Error(`mcpServe('${serverName}'): tool '${name}' declares needs.credential ` +
192
+ `'${tool.needs.credential}' but no credential provider was passed. Pass ` +
193
+ `mcpServe(tools, { credentials }) so the credential is resolved before execute, ` +
194
+ `the same way the Agent resolves it.`);
195
+ }
196
+ byName.set(name, tool);
197
+ }
198
+ return byName;
199
+ }
200
+ // ─── Per-call execution context ────────────────────────────────────
201
+ /**
202
+ * Assemble the `ToolExecutionContext` for one served call, resolving a
203
+ * declared credential first. Returns `{ blocked }` instead of throwing
204
+ * when the credential is unavailable, so the client is told WHY in a
205
+ * tool-error result rather than seeing a generic failure.
206
+ */
207
+ async function buildExecutionContext(tool, toolCallId, wiring) {
208
+ const { credentials, hasCredentials, signal } = wiring;
209
+ let credential;
210
+ const need = tool.needs;
211
+ if (need) {
212
+ const resolved = await credentials.getCredential({
213
+ service: need.credential,
214
+ ...(need.scopes && { scopes: need.scopes }),
215
+ ...(need.mode && { mode: need.mode }),
216
+ });
217
+ // Fail-closed, mirroring the Agent's tool-call stage: a tool that
218
+ // asked for a credential never runs without one.
219
+ if (resolved.status !== 'issued') {
220
+ return {
221
+ blocked: `authorization required for '${need.credential}': ${resolved.authorizationUrl}`,
222
+ };
223
+ }
224
+ credential = resolved.credential;
225
+ }
226
+ return {
227
+ context: {
228
+ toolCallId,
229
+ // There is no ReAct loop out here — a served call is a single
230
+ // request, so the iteration a tool might branch on is zero.
231
+ iteration: 0,
232
+ credentials,
233
+ hasCredentials,
234
+ ...(signal && { signal }),
235
+ ...(credential && { credential }),
236
+ },
237
+ };
238
+ }
239
+ // ─── Result mapping ────────────────────────────────────────────────
240
+ /** MCP carries text blocks; a Tool returns anything JSON-serializable. */
241
+ function stringifyResult(result) {
242
+ if (typeof result === 'string')
243
+ return result;
244
+ if (result === undefined)
245
+ return '';
246
+ try {
247
+ return JSON.stringify(result) ?? String(result);
248
+ }
249
+ catch {
250
+ // Circular or otherwise unserializable — say so rather than throwing
251
+ // from the happy path.
252
+ return String(result);
253
+ }
254
+ }
255
+ /** A tool-level error: reported IN the result, per the MCP spec, not thrown. */
256
+ function toolError(message) {
257
+ return { content: [{ type: 'text', text: message }], isError: true };
258
+ }
259
+ // ─── SDK construction (lazy require) ───────────────────────────────
260
+ async function resolveServer(name, version) {
261
+ let mod;
262
+ try {
263
+ mod = (0, lazyRequire_js_1.lazyRequire)('@modelcontextprotocol/sdk/server/index.js');
264
+ }
265
+ catch {
266
+ throw new Error('mcpServe requires @modelcontextprotocol/sdk.\n' +
267
+ ' Install: npm install @modelcontextprotocol/sdk\n' +
268
+ ' Or pass `_server` for test injection.');
269
+ }
270
+ return new mod.Server({ name, version }, { capabilities: { tools: {} } });
271
+ }
272
+ /**
273
+ * The request schemas the SDK dispatches on. With an injected `_server`
274
+ * there is no SDK to read them from, so tests get stable sentinel
275
+ * objects — the injected server decides what to do with them.
276
+ */
277
+ async function resolveRequestSchemas(injected) {
278
+ if (injected) {
279
+ return { listSchema: exports.LIST_TOOLS_SENTINEL, callSchema: exports.CALL_TOOL_SENTINEL };
280
+ }
281
+ let types;
282
+ try {
283
+ types = (0, lazyRequire_js_1.lazyRequire)('@modelcontextprotocol/sdk/types.js');
284
+ }
285
+ catch {
286
+ throw new Error('mcpServe requires @modelcontextprotocol/sdk/types.js — check that ' +
287
+ '@modelcontextprotocol/sdk is installed at the latest version.');
288
+ }
289
+ return { listSchema: types.ListToolsRequestSchema, callSchema: types.CallToolRequestSchema };
290
+ }
291
+ /**
292
+ * Sentinels handed to an injected `_server` in place of the SDK's zod
293
+ * schemas. Exported so a test can tell the two handlers apart.
294
+ * @internal
295
+ */
296
+ exports.LIST_TOOLS_SENTINEL = Object.freeze({ method: 'tools/list' });
297
+ /** @internal @see LIST_TOOLS_SENTINEL */
298
+ exports.CALL_TOOL_SENTINEL = Object.freeze({ method: 'tools/call' });
299
+ /**
300
+ * For stdio and for an injected test server there is nothing extra to
301
+ * unwind: the SDK's own `server.close()` closes the transport it is
302
+ * connected to. Only the HTTP path owns a socket of its own.
303
+ */
304
+ const NOTHING_TO_UNWIND = { close: () => Promise.resolve() };
305
+ async function connectTransport(sdk, transport, opts, newServer) {
306
+ // An injected server is a test double: there is no real transport to
307
+ // build, and building one would spawn a listener or seize stdio.
308
+ if (opts._server) {
309
+ await sdk.connect(undefined);
310
+ return NOTHING_TO_UNWIND;
311
+ }
312
+ if (transport.transport === 'stdio') {
313
+ let stdioMod;
314
+ try {
315
+ stdioMod = (0, lazyRequire_js_1.lazyRequire)('@modelcontextprotocol/sdk/server/stdio.js');
316
+ }
317
+ catch {
318
+ throw new Error('mcpServe(stdio) requires @modelcontextprotocol/sdk/server/stdio.js — ' +
319
+ 'check that @modelcontextprotocol/sdk is installed at the latest version.');
320
+ }
321
+ await sdk.connect(new stdioMod.StdioServerTransport());
322
+ return NOTHING_TO_UNWIND;
323
+ }
324
+ // HTTP deliberately does not use `sdk`: it mints a server per request
325
+ // (see connectHttp). The root server stays unconnected, which makes the
326
+ // handle's `sdk.close()` a harmless no-op on this path.
327
+ return connectHttp(transport, newServer);
328
+ }
329
+ /**
330
+ * Streamable HTTP. The SDK's transport handles the protocol but does not
331
+ * own a socket — it expects to be driven from a request handler — so the
332
+ * listener is ours, built on node:http (built in; no new dependency).
333
+ *
334
+ * Stateless (`sessionIdGenerator: undefined`): no session table to keep,
335
+ * nothing to expire, and several replicas can serve the same tools.
336
+ *
337
+ * Statelessness is not just a config flag here — it decides the shape of
338
+ * this function. The SDK's stateless transport is single-use by design
339
+ * (reusing one would let two clients collide on JSON-RPC message ids), so
340
+ * it throws on its second request. Each request therefore gets its own
341
+ * transport, and — because one SDK server can only be attached to one
342
+ * transport — its own server. Both are thrown away when the response
343
+ * closes. The tools they serve are the same objects either way.
344
+ */
345
+ async function connectHttp(transport, newServer) {
346
+ let httpMod;
347
+ try {
348
+ httpMod = (0, lazyRequire_js_1.lazyRequire)('@modelcontextprotocol/sdk/server/streamableHttp.js');
349
+ }
350
+ catch {
351
+ throw new Error('mcpServe(http) requires @modelcontextprotocol/sdk/server/streamableHttp.js — ' +
352
+ 'check that @modelcontextprotocol/sdk is installed at the latest version.');
353
+ }
354
+ const { createServer } = await Promise.resolve().then(() => __importStar(require('node:http')));
355
+ const serveOne = async (req, res) => {
356
+ const server = await newServer();
357
+ const mcpTransport = new httpMod.StreamableHTTPServerTransport({
358
+ sessionIdGenerator: undefined,
359
+ });
360
+ // The pair lives exactly as long as the response does.
361
+ res.on('close', () => {
362
+ void mcpTransport.close();
363
+ void server.close();
364
+ });
365
+ await server.connect(mcpTransport);
366
+ await mcpTransport.handleRequest(req, res);
367
+ };
368
+ const path = transport.path ?? DEFAULT_HTTP_PATH;
369
+ const listener = createServer((req, res) => {
370
+ // Route on the path only; the transport itself decides which HTTP
371
+ // methods it accepts on the MCP endpoint.
372
+ const url = req.url ?? '';
373
+ if (url.split('?')[0] !== path) {
374
+ res.statusCode = 404;
375
+ res.end();
376
+ return;
377
+ }
378
+ // One failed request must not take the listener down. The client is
379
+ // told (500 is a protocol-level error it surfaces); the next request
380
+ // is served normally.
381
+ void serveOne(req, res).catch(() => {
382
+ if (!res.headersSent) {
383
+ res.statusCode = 500;
384
+ res.end();
385
+ }
386
+ });
387
+ });
388
+ await new Promise((resolve, reject) => {
389
+ listener.once('error', reject);
390
+ if (transport.host !== undefined)
391
+ listener.listen(transport.port, transport.host, resolve);
392
+ else
393
+ listener.listen(transport.port, resolve);
394
+ });
395
+ return {
396
+ close: () => new Promise((resolve, reject) => {
397
+ listener.close((err) => (err ? reject(err) : resolve()));
398
+ }),
399
+ };
400
+ }
401
+ //# sourceMappingURL=mcpServe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcpServe.js","sourceRoot":"","sources":["../../../src/lib/mcp/mcpServe.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;;;;;;;;;;;;;;;;;;;;;;;;;;AAQH,sDAAyE;AASzE,sDAAgD;AAEhD,MAAM,mBAAmB,GAAG,gBAAgB,CAAC;AAC7C,MAAM,sBAAsB,GAAG,OAAO,CAAC;AACvC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AAEjC;;;;;;;;;GASG;AACI,KAAK,UAAU,QAAQ,CAC5B,KAAsB,EACtB,OAAwB,EAAE;IAE1B,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,mBAAmB,CAAC;IAC9C,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,sBAAsB,CAAC;IACvD,MAAM,MAAM,GAAG,qBAAqB,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IACpE,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,IAAA,yCAA8B,GAAE,CAAC;IAEzE,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;QAChC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI;QACnB,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,WAAW,KAAK,SAAS,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC;QAChF,WAAW,EAAE,CAAC,CA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-1,12 +1,15 @@
1
1
  "use strict";
2
2
  /**
3
- * MCP — Model Context Protocol client integration.
3
+ * MCP — Model Context Protocol, in both directions.
4
4
  *
5
5
  * MCP (https://modelcontextprotocol.io) is an open standard for
6
- * connecting LLMs to external tools and data sources. agentfootprint's
7
- * MCP adapter is **client-only** — it consumes MCP servers and exposes
8
- * their tools as agentfootprint `Tool[]` so consumers can plug them
9
- * straight into `agent.tool(...)`.
6
+ * connecting LLMs to external tools and data sources. This module
7
+ * bridges it both ways:
8
+ *
9
+ * - `mcpClient(opts)` — consume an MCP server; its tools become
10
+ * agentfootprint `Tool[]` you can hand to `agent.tools(...)`.
11
+ * - `mcpServe(tools, opts)` — the other direction: expose your own
12
+ * `Tool[]` AS an MCP server, so any MCP client can call them.
10
13
  *
11
14
  * Pattern: Adapter (GoF) — translates MCP wire format ↔ agentfootprint
12
15
  * `Tool` interface. The MCP SDK does the protocol work; we
@@ -15,11 +18,8 @@
15
18
  * inline alternative for non-MCP tools).
16
19
  * Emits: N/A directly — wrapped tools emit the standard
17
20
  * `agentfootprint.stream.tool_start` / `tool_end` events
18
- * when the agent calls them.
19
- *
20
- * Server-side support (exposing an agent or LLMCall as an MCP tool)
21
- * is a separate concern not yet shipped. This module covers the
22
- * 80% case: pulling an existing MCP server's tools INTO an agent.
21
+ * when the agent calls them. `mcpServe` runs OUTSIDE any
22
+ * agent run, so it emits nothing at all.
23
23
  */
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
25
  //# sourceMappingURL=types.js.map
@@ -14,6 +14,12 @@
14
14
  * - `mcpClient(opts)` — connect to an MCP server (real)
15
15
  * - `mockMcpClient({ tools })` — in-memory MCP source for dev / tests
16
16
  *
17
+ * 3. Tool sink — the other direction
18
+ * - `mcpServe(tools, opts)` — expose your own `Tool[]` AS an MCP
19
+ * server, so any MCP client can call them. The served tool is the
20
+ * SAME object you pass in, so whatever governance you composed
21
+ * around it still runs.
22
+ *
17
23
  * Compose freely. The dispatch layer is decorator-shaped (mirroring
18
24
  * `withRetry` / `withFallback` over LLMProvider). Tool sources produce
19
25
  * `Tool[]` that flow into a `staticTools(arr)` provider, which can
@@ -35,7 +41,7 @@
35
41
  * const provider = gatedTools(staticTools(slackTools), (name) => allowed(name));
36
42
  */
37
43
  Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.mockMcpClient = exports.mcpClient = exports.skillScopedTools = exports.gatedTools = exports.staticTools = void 0;
44
+ exports.mockMcpClient = exports.mcpServe = exports.mcpClient = exports.skillScopedTools = exports.gatedTools = exports.staticTools = void 0;
39
45
  var staticTools_js_1 = require("./staticTools.js");
40
46
  Object.defineProperty(exports, "staticTools", { enumerable: true, get: function () { return staticTools_js_1.staticTools; } });
41
47
  var gatedTools_js_1 = require("./gatedTools.js");
@@ -47,5 +53,6 @@ Object.defineProperty(exports, "skillScopedTools", { enumerable: true, get: func
47
53
  // top-level barrel does not re-export it.
48
54
  var index_js_1 = require("../lib/mcp/index.js");
49
55
  Object.defineProperty(exports, "mcpClient", { enumerable: true, get: function () { return index_js_1.mcpClient; } });
56
+ Object.defineProperty(exports, "mcpServe", { enumerable: true, get: function () { return index_js_1.mcpServe; } });
50
57
  Object.defineProperty(exports, "mockMcpClient", { enumerable: true, get: function () { return index_js_1.mockMcpClient; } });
51
58
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tool-providers/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;;;AAEH,mDAA+C;AAAtC,6GAAA,WAAW,OAAA;AACpB,iDAA6C;AAApC,2GAAA,UAAU,OAAA;AACnB,6DAAyD;AAAhD,uHAAA,gBAAgB,OAAA;AAGzB,uEAAuE;AACvE,wEAAwE;AACxE,0CAA0C;AAC1C,gDAA+D;AAAtD,qGAAA,SAAS,OAAA;AAAE,yGAAA,aAAa,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/tool-providers/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;;;AAEH,mDAA+C;AAAtC,6GAAA,WAAW,OAAA;AACpB,iDAA6C;AAApC,2GAAA,UAAU,OAAA;AACnB,6DAAyD;AAAhD,uHAAA,gBAAgB,OAAA;AAGzB,uEAAuE;AACvE,wEAAwE;AACxE,0CAA0C;AAC1C,gDAAyE;AAAhE,qGAAA,SAAS,OAAA;AAAE,oGAAA,QAAQ,OAAA;AAAE,yGAAA,aAAa,OAAA"}
@@ -27,11 +27,11 @@ import { type OutputSchemaParser } from './outputSchema.js';
27
27
  import { RunnerBase } from './RunnerBase.js';
28
28
  import type { ToolRegistryEntry } from './tools.js';
29
29
  import type { ToolProvider } from '../tool-providers/types.js';
30
- import type { AgentInput, AgentOptions, AgentOutput, ObserverDeliveryOptions } from './agent/types.js';
30
+ import type { AgentInput, AgentOptions, AgentOutput, ObserverDeliveryOptions, RunConfig, RunConfigContext, RunConfigFn, WriteProvenanceMode } from './agent/types.js';
31
31
  import { AgentBuilder } from './agent/AgentBuilder.js';
32
32
  import type { ThinkingHandler } from '../thinking/types.js';
33
33
  export { AgentBuilder };
34
- export type { AgentInput, AgentOptions, AgentOutput, ObserverDeliveryOptions };
34
+ export type { AgentInput, AgentOptions, AgentOutput, ObserverDeliveryOptions, RunConfig, RunConfigContext, RunConfigFn, WriteProvenanceMode, };
35
35
  /**
36
36
  * `RunOptions` (footprintjs) + agentfootprint-domain correlation fields.
37
37
  *
@@ -110,6 +110,10 @@ export declare class Agent extends RunnerBase<AgentInput, AgentOutput> {
110
110
  * present — defaults to `standard` evidence + the lexical scorer, so a tool
111
111
  * that declares `checkIn` works even without a `.checkIn()` builder call. */
112
112
  private readonly checkInConfig;
113
+ /** Per-run config resolver from `.configure()`. Undefined for every agent
114
+ * that never called it — and the chart is then built exactly as before,
115
+ * with no scope writes and no scope reads added. */
116
+ private readonly runConfigFn?;
113
117
  /** Snapshot read-tracking policy (#18/#14) — forwarded to the internal
114
118
  * executor. Agent default is `'summary'` (cheap markers), NOT
115
119
  * footprintjs's `'full'`. See AgentOptions.readTracking. */
@@ -120,6 +124,10 @@ export declare class Agent extends RunnerBase<AgentInput, AgentOutput> {
120
124
  * retained memory), NOT footprintjs's `'full'`. See
121
125
  * AgentOptions.commitValues. */
122
126
  private readonly commitValues;
127
+ /** Per-write read provenance (#P1) — forwarded to the internal executor.
128
+ * Default `'off'` (footprintjs's own): recordings stay byte-identical
129
+ * unless a consumer opts in. See AgentOptions.writeProvenance. */
130
+ private readonly writeProvenance;
123
131
  private readonly credentialProvider?;
124
132
  /** Evidence bridge (#5) — present iff a CAUSAL memory is mounted. */
125
133
  private readonly causalEvidence?;
@@ -216,7 +224,7 @@ export declare class Agent extends RunnerBase<AgentInput, AgentOutput> {
216
224
  readonly appName: string;
217
225
  readonly commentaryTemplates: Readonly<Record<string, string>>;
218
226
  readonly thinkingTemplates: Readonly<Record<string, string>>;
219
- }, injections?: readonly Injection[], memories?: readonly MemoryDefinition[], outputSchemaParser?: OutputSchemaParser<unknown>, toolProvider?: ToolProvider, systemPromptCachePolicy?: CachePolicy, cachingDisabled?: boolean, cacheStrategy?: CacheStrategy, outputFallbackCfg?: ResolvedOutputFallback<unknown>, reliabilityConfig?: ReliabilityConfig, thinkingHandlerValue?: ThinkingHandler | null, thinkingBudgetValue?: number, skillGraphNextSkill?: (ctx: InjectionContext) => string | undefined, skillGraphReachable?: (currentSkillId?: string) => readonly string[], skillGraphScoreEntries?: (ctx: InjectionContext, signal?: AbortSignal) => Promise<EntryScoring>, checkInOptions?: CheckInBuilderOptions);
227
+ }, injections?: readonly Injection[], memories?: readonly MemoryDefinition[], outputSchemaParser?: OutputSchemaParser<unknown>, toolProvider?: ToolProvider, systemPromptCachePolicy?: CachePolicy, cachingDisabled?: boolean, cacheStrategy?: CacheStrategy, outputFallbackCfg?: ResolvedOutputFallback<unknown>, reliabilityConfig?: ReliabilityConfig, thinkingHandlerValue?: ThinkingHandler | null, thinkingBudgetValue?: number, skillGraphNextSkill?: (ctx: InjectionContext) => string | undefined, skillGraphReachable?: (currentSkillId?: string) => readonly string[], skillGraphScoreEntries?: (ctx: InjectionContext, signal?: AbortSignal) => Promise<EntryScoring>, checkInOptions?: CheckInBuilderOptions, runConfigFn?: RunConfigFn);
220
228
  static create(opts: AgentOptions): AgentBuilder;
221
229
  /**
222
230
  * Cache policy for the base system prompt. Read by the CacheDecision
@@ -1 +1 @@
1
- {"version":3,"file":"Agent.d.ts","sourceRoot":"","sources":["../../../src/core/Agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAGL,KAAK,sBAAsB,EAI3B,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EAExB,KAAK,UAAU,EACf,KAAK,eAAe,EACrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAOjE,OAAO,EAAE,KAAK,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAyBrD,OAAO,EAEL,KAAK,qBAAqB,EAE3B,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AASlE,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AACpF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uCAAuC,CAAC;AAE1E,OAAO,EAAuB,KAAK,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AACvF,OAAO,EAKL,KAAK,kBAAkB,EAExB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAwC,KAAK,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAClG,OAAO,EAAE,UAAU,EAAa,MAAM,iBAAiB,CAAC;AACxD,OAAO,KAAK,EAAE,iBA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;;;;;;;;;;;;;;;;OAmBG;IACH,cAAc,CAAC,IAAI,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAK3E,OAAO,CAAC,cAAc;IA8FtB,OAAO,CAAC,UAAU;CA6MnB"}
@@ -19,7 +19,7 @@ import type { CheckInBuilderOptions } from '../checkin.js';
19
19
  import type { ToolProvider } from '../../tool-providers/types.js';
20
20
  import { type SelfExplainOptions } from '../../lib/trace-toolpack/selfExplain.js';
21
21
  import { Agent } from '../Agent.js';
22
- import type { AgentOptions } from './types.js';
22
+ import type { AgentOptions, RunConfigFn } from './types.js';
23
23
  /**
24
24
  * Fluent builder. `tool()` accepts any Tool<TArgs, TResult> and registers
25
25
  * it by its schema.name. Duplicate names throw at build time.
@@ -121,6 +121,9 @@ export declare class AgentBuilder {
121
121
  private thinkingBudgetValue?;
122
122
  private selfExplainConfig?;
123
123
  private checkInConfig?;
124
+ /** Per-run config resolver set via `.configure()`. Undefined = the agent
125
+ * runs on its build-time model + system prompt, unchanged. */
126
+ private runConfigFn?;
124
127
  constructor(opts: AgentOptions);
125
128
  /**
126
129
  * Set the base system prompt.
@@ -183,6 +186,50 @@ export declare class AgentBuilder {
183
186
  * .build();
184
187
  */
185
188
  toolProvider(provider: ToolProvider): this;
189
+ /**
190
+ * Decide this run's model and/or system prompt when the run starts.
191
+ *
192
+ * An agent is built once and run many times, but not every run wants the
193
+ * same model or the same instructions: a long message may deserve the
194
+ * bigger model, a tenant may have its own house rules, a canary may want
195
+ * last week's prompt. Rebuilding the whole agent per request works and is
196
+ * wasteful; reaching in and mutating one is worse, because the trace then
197
+ * describes an agent that no longer exists.
198
+ *
199
+ * The resolver runs ONCE per `run()`, at the start of the run, and what it
200
+ * returns is **committed to the trace** — `resolvedModel` and
201
+ * `resolvedInstructions` land in the run's commit log before the first LLM
202
+ * call, and the LLM call reads them from there. So the recording says which
203
+ * model actually answered instead of which model the agent was built with.
204
+ *
205
+ * Return `{}` (or nothing) to keep the defaults; `ctx.defaults` carries
206
+ * them, so a resolver can decide relative to what was built rather than
207
+ * restating it. Omit `.configure()` entirely and every run behaves — and
208
+ * records — exactly as it did before.
209
+ *
210
+ * This is the RUN axis only. Tools are the iteration axis and already have
211
+ * an owner: `.toolProvider()`, consulted every iteration.
212
+ *
213
+ * Throws if called more than once (same rule as `.toolProvider()` — a
214
+ * silently-overridden resolver is a config that lies).
215
+ *
216
+ * @example Bigger model for a bigger question
217
+ * const agent = Agent.create({ provider, model: 'small-model' })
218
+ * .system('You answer support questions.')
219
+ * .configure(({ message, defaults }) =>
220
+ * message.length > 500 ? { model: 'big-model' } : {},
221
+ * )
222
+ * .build();
223
+ *
224
+ * @example Per-tenant house rules
225
+ * const agent = Agent.create({ provider, model })
226
+ * .system('You answer support questions.')
227
+ * .configure(({ identity, defaults }) => ({
228
+ * instructions: `${defaults.instructions}\n\n${rulesFor(identity?.tenant)}`,
229
+ * }))
230
+ * .build();
231
+ */
232
+ configure(fn: RunConfigFn): this;
186
233
  /**
187
234
  * Override the ReAct iteration cap set via `Agent.create({
188
235
  * maxIterations })`. Convenience for builder-style code that prefers