@tinyweb_dev/agent-framework-agent 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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@tinyweb_dev/agent-framework-agent",
4
- "version": "0.1.0",
4
+ "version": "0.2.0",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "scripts": {
@@ -34,8 +34,8 @@
34
34
  "drizzle-orm": "1.0.0-beta.19-d95b7a4",
35
35
  "effect": "4.0.0-beta.59",
36
36
  "ulid": "3.0.1",
37
- "@tinyweb_dev/agent-framework-core": "0.1.0",
38
- "@tinyweb_dev/agent-framework-llm": "0.1.0",
39
- "@tinyweb_dev/agent-framework-protocol": "0.1.0"
37
+ "@tinyweb_dev/agent-framework-core": "0.2.0",
38
+ "@tinyweb_dev/agent-framework-llm": "0.2.0",
39
+ "@tinyweb_dev/agent-framework-protocol": "0.2.0"
40
40
  }
41
41
  }
package/src/agent.ts CHANGED
@@ -13,12 +13,18 @@ import type { AttachmentInput } from "./attachments"
13
13
  import { compact } from "./session/compaction"
14
14
  import { estimateTokens, usable } from "./session/overflow"
15
15
  import { type AgentEvent } from "./events"
16
- import { applyPermission, type PermissionAskHandler, type PermissionConfig } from "./permission"
16
+ import {
17
+ applyPermission,
18
+ type PermissionAskHandler,
19
+ type PermissionAskMode,
20
+ type PermissionConfig,
21
+ } from "./permission"
17
22
  import { defaultRuntime, type AgentRuntime } from "./runtime"
18
- import { makeProcessor } from "./session/processor"
23
+ import { makeProcessor, persistMessageUpdate } from "./session/processor"
19
24
  import { makeMemoryStore } from "./session/memory"
20
25
  import type { SessionStore } from "./session/adapter"
21
26
  import { historyToLLMMessages } from "./session/replay"
27
+ import type { AssistantMessage, Message, ToolPart } from "./session/schema"
22
28
  import { makeSSEHandler, type SSEHandlerOptions } from "./sse-handler"
23
29
  import { loadPlugins, type Hooks, type PluginEntry } from "./plugin"
24
30
  import { connectAllMcp, type McpConfig } from "./mcp"
@@ -67,6 +73,13 @@ export type DefineAgentConfig<T extends Tools> = {
67
73
  readonly store?: SessionStore
68
74
  readonly permission?: PermissionConfig
69
75
  readonly askHandler?: PermissionAskHandler
76
+ /**
77
+ * How `"ask"` permission rules are enforced.
78
+ * - `"handler"` (default) — block on `askHandler` Promise (CLI / in-process UI).
79
+ * - `"interrupt"` — persist `pending-approval` ToolPart and stop the turn;
80
+ * host later calls `resolveApproval` + `resume`. Preferred for durable UIs.
81
+ */
82
+ readonly askMode?: PermissionAskMode
70
83
  /** Plugins to load — inline Plugin fn, path string, or [path, options] tuple */
71
84
  readonly plugins?: PluginEntry[]
72
85
  /** MCP servers to connect — Record<serverName, McpServerConfig> */
@@ -83,6 +96,24 @@ export type RunInput = {
83
96
  readonly attachments?: ReadonlyArray<AttachmentInput>
84
97
  }
85
98
 
99
+ export type ResumeInput = {
100
+ readonly sessionId: string
101
+ }
102
+
103
+ export type ResolveApprovalInput = {
104
+ readonly sessionId: string
105
+ /** Tool call id (`ToolPart.callID` / SSE `tool-approval-request.id`). */
106
+ readonly callID: string
107
+ readonly approved: boolean
108
+ }
109
+
110
+ export type ResolveApprovalResult = {
111
+ readonly callID: string
112
+ readonly state: "approved" | "rejected"
113
+ readonly toolName: string
114
+ readonly input: unknown
115
+ }
116
+
86
117
  export type RunOnceResult = {
87
118
  readonly text: string
88
119
  readonly usage: LLMResponse["usage"]
@@ -98,6 +129,16 @@ export type Agent = {
98
129
  readonly name: string
99
130
  readonly run: (input: RunInput) => AsyncIterable<AgentEvent>
100
131
  readonly runOnce: (input: RunInput) => Promise<RunOnceResult>
132
+ /**
133
+ * Mark a `pending-approval` tool call as approved or rejected (persisted in
134
+ * the SessionStore). Does NOT execute the tool — call `resume` afterwards.
135
+ */
136
+ readonly resolveApproval: (input: ResolveApprovalInput) => Promise<ResolveApprovalResult>
137
+ /**
138
+ * Continue a session after approvals were resolved. Executes approved tools,
139
+ * records denials, then streams a follow-up LLM turn.
140
+ */
141
+ readonly resume: (input: ResumeInput) => AsyncIterable<AgentEvent>
101
142
  readonly toSSEHandler: (options?: SSEHandlerOptions) => ReturnType<typeof makeSSEHandler>
102
143
  readonly sessions: SessionAPI
103
144
  readonly toHTTPHandlers: (options?: ToHTTPHandlersOptions) => HTTPHandlers
@@ -117,7 +158,14 @@ const getDefaultStore = (): SessionStore => {
117
158
  // buildTools — merge user tools + MCP tools + optional skill tool
118
159
  // ---------------------------------------------------------------------------
119
160
 
120
- async function buildTools(
161
+ type BuiltTools = {
162
+ /** Permission-wrapped tools for the normal agentic loop. */
163
+ readonly tools: ExecutableTools
164
+ /** Unwrapped tools for resume (execute host-approved calls). */
165
+ readonly resumeTools: ExecutableTools
166
+ }
167
+
168
+ async function buildMergedTools(
121
169
  config: DefineAgentConfig<Tools>,
122
170
  loadedHooks: Hooks[],
123
171
  ): Promise<ExecutableTools> {
@@ -152,7 +200,19 @@ async function buildTools(
152
200
  }
153
201
  }
154
202
 
155
- return applyPermission(merged, config.permission, config.askHandler)
203
+ return merged
204
+ }
205
+
206
+ async function buildTools(
207
+ config: DefineAgentConfig<Tools>,
208
+ loadedHooks: Hooks[],
209
+ ): Promise<BuiltTools> {
210
+ const merged = await buildMergedTools(config, loadedHooks)
211
+ const askMode = config.askMode ?? "handler"
212
+ return {
213
+ tools: applyPermission(merged, config.permission, config.askHandler, askMode),
214
+ resumeTools: merged,
215
+ }
156
216
  }
157
217
 
158
218
  // ---------------------------------------------------------------------------
@@ -181,137 +241,230 @@ export const defineAgent = <T extends Tools = Tools>(config: DefineAgentConfig<T
181
241
  }
182
242
 
183
243
  // Build tools lazily on first use (async — MCP / skills may need network/fs)
184
- let toolsPromise: Promise<ExecutableTools> | undefined
185
-
186
- const getTools = (): Promise<ExecutableTools> => {
187
- if (!toolsPromise) {
188
- const pluginInput = { agentName: config.name, directory: process.cwd() }
189
- toolsPromise = loadPlugins(config.plugins ?? [], pluginInput).then((loaded) => {
190
- const hooks = loaded.map((l) => l.hooks)
191
- return buildTools(config, hooks)
244
+ let toolsPromise: Promise<BuiltTools> | undefined
245
+
246
+ const getTools = (): Promise<BuiltTools> => {
247
+ if (!toolsPromise) {
248
+ const pluginInput = { agentName: config.name, directory: process.cwd() }
249
+ toolsPromise = loadPlugins(config.plugins ?? [], pluginInput).then((loaded) => {
250
+ const hooks = loaded.map((l) => l.hooks)
251
+ return buildTools(config, hooks)
252
+ })
253
+ }
254
+ return toolsPromise
255
+ }
256
+
257
+ const makeAgentProcessor = async () => {
258
+ const built = await getTools()
259
+ return makeProcessor({
260
+ agentName: config.name,
261
+ model: config.model,
262
+ store,
263
+ runtime: rt(),
264
+ systemPrompt: resolvedSystemPrompt,
265
+ tools: built.tools,
266
+ resumeTools: built.resumeTools,
267
+ stopWhen,
268
+ generation: config.generation,
269
+ compaction: compactionCfg,
192
270
  })
193
271
  }
194
- return toolsPromise
195
- }
196
-
197
- const run = (input: RunInput): AsyncIterable<AgentEvent> => {
198
- // Return an AsyncIterable that initialises tools once then delegates to processor
199
- let innerIter: AsyncIterator<AgentEvent> | undefined
200
- return {
201
- [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
202
- return {
203
- async next() {
204
- if (!innerIter) {
205
- const tools = await getTools()
206
- const processor = makeProcessor({
207
- agentName: config.name,
208
- model: config.model,
209
- store,
210
- runtime: rt(),
211
- systemPrompt: resolvedSystemPrompt,
212
- tools,
213
- stopWhen,
214
- generation: config.generation,
215
- compaction: compactionCfg,
216
- })
217
- innerIter = processor.runTurn(input)[Symbol.asyncIterator]()
218
- }
219
- return innerIter.next()
220
- },
221
- async return(value) {
222
- return innerIter ? (innerIter.return ? innerIter.return(value) : { done: true, value }) : { done: true, value }
223
- },
224
- }
225
- },
272
+
273
+ const run = (input: RunInput): AsyncIterable<AgentEvent> => {
274
+ let innerIter: AsyncIterator<AgentEvent> | undefined
275
+ return {
276
+ [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
277
+ return {
278
+ async next() {
279
+ if (!innerIter) {
280
+ const processor = await makeAgentProcessor()
281
+ innerIter = processor.runTurn(input)[Symbol.asyncIterator]()
282
+ }
283
+ return innerIter.next()
284
+ },
285
+ async return(value) {
286
+ return innerIter
287
+ ? innerIter.return
288
+ ? innerIter.return(value)
289
+ : { done: true, value }
290
+ : { done: true, value }
291
+ },
292
+ }
293
+ },
294
+ }
226
295
  }
227
- }
228
-
229
- const runOnce = async (input: RunInput): Promise<RunOnceResult> => {
230
- const tools = await getTools()
231
- const budget = usable({
232
- limits: config.model.limits,
233
- reservedTokens: compactionCfg.reservedTokens,
234
- })
235
- const keepRecent = compactionCfg.preserveRecentTurns ?? 4
236
-
237
- const result = await rt().runPromise(
238
- Effect.gen(function* () {
239
- const session = yield* store.upsertSession({ id: input.sessionId, agentName: config.name })
240
-
241
- // Pre-flight: compact if estimate would overflow the usable budget.
242
- if (compactionCfg.auto) {
243
- const history = yield* store.getMessages(session.id)
244
- const promptTokens = Math.ceil(input.prompt.length / 4)
245
- const systemTokens = Math.ceil(resolvedSystemPrompt.length / 4)
246
- if (estimateTokens(history) + promptTokens + systemTokens >= budget) {
247
- yield* compact({
248
- sessionId: session.id,
249
- store,
250
- model: config.model,
251
- keepRecent,
252
- overflow: false,
253
- })
296
+
297
+ const resume = (input: ResumeInput): AsyncIterable<AgentEvent> => {
298
+ let innerIter: AsyncIterator<AgentEvent> | undefined
299
+ return {
300
+ [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
301
+ return {
302
+ async next() {
303
+ if (!innerIter) {
304
+ const processor = await makeAgentProcessor()
305
+ innerIter = processor.resumeTurn({ sessionId: input.sessionId })[Symbol.asyncIterator]()
306
+ }
307
+ return innerIter.next()
308
+ },
309
+ async return(value) {
310
+ return innerIter
311
+ ? innerIter.return
312
+ ? innerIter.return(value)
313
+ : { done: true, value }
314
+ : { done: true, value }
315
+ },
254
316
  }
317
+ },
318
+ }
319
+ }
320
+
321
+ const resolveApproval = async (input: ResolveApprovalInput): Promise<ResolveApprovalResult> => {
322
+ const history = await rt().runPromise(store.getMessages(input.sessionId))
323
+ let targetMsg: AssistantMessage | undefined
324
+ let targetPart: ToolPart | undefined
325
+ let partIndex = -1
326
+
327
+ for (let i = history.length - 1; i >= 0; i--) {
328
+ const msg = history[i]
329
+ if (!msg || msg.role !== "assistant") continue
330
+ const idx = msg.parts.findIndex(
331
+ (p) =>
332
+ (p as ToolPart).type === "tool" &&
333
+ (p as ToolPart).callID === input.callID &&
334
+ (p as ToolPart).state === "pending-approval",
335
+ )
336
+ if (idx !== -1) {
337
+ targetMsg = msg as AssistantMessage
338
+ targetPart = msg.parts[idx] as ToolPart
339
+ partIndex = idx
340
+ break
255
341
  }
256
-
257
- const attempt = () =>
258
- Effect.gen(function* () {
342
+ }
343
+
344
+ if (!targetMsg || !targetPart || partIndex < 0) {
345
+ throw new Error(`No pending approval found for callID="${input.callID}"`)
346
+ }
347
+
348
+ const nextState = input.approved ? ("approved" as const) : ("rejected" as const)
349
+ const nextParts = targetMsg.parts.map((p, idx) =>
350
+ idx === partIndex ? ({ ...targetPart!, state: nextState } satisfies ToolPart) : p,
351
+ )
352
+ const updated: AssistantMessage = { ...targetMsg, parts: nextParts }
353
+ await rt().runPromise(persistMessageUpdate(store, input.sessionId, updated as Message))
354
+
355
+ return {
356
+ callID: input.callID,
357
+ state: nextState,
358
+ toolName: targetPart.name,
359
+ input: targetPart.input,
360
+ }
361
+ }
362
+
363
+ const runOnce = async (input: RunInput): Promise<RunOnceResult> => {
364
+ const { tools } = await getTools()
365
+ const budget = usable({
366
+ limits: config.model.limits,
367
+ reservedTokens: compactionCfg.reservedTokens,
368
+ })
369
+ const keepRecent = compactionCfg.preserveRecentTurns ?? 4
370
+
371
+ const result = await rt().runPromise(
372
+ Effect.gen(function* () {
373
+ const session = yield* store.upsertSession({ id: input.sessionId, agentName: config.name })
374
+
375
+ // Pre-flight: compact if estimate would overflow the usable budget.
376
+ if (compactionCfg.auto) {
259
377
  const history = yield* store.getMessages(session.id)
260
- const userContent: Array<{ type: "text"; text: string } | { type: "media"; mediaType: string; data: string; filename?: string }> = []
261
- if (input.prompt.length > 0) userContent.push({ type: "text", text: input.prompt })
262
- for (const a of input.attachments ?? [])
263
- userContent.push({ type: "media", mediaType: a.mediaType, data: a.url ?? a.data ?? "", filename: a.filename })
264
- const userMsg = userContent.length === 0 ? LLM.user(input.prompt) : LLM.user(userContent)
265
- const request = LLM.request({
266
- model: config.model,
267
- system: resolvedSystemPrompt,
268
- messages: [...historyToLLMMessages([...history]), userMsg],
269
- generation: config.generation,
270
- })
271
- return yield* LLMClient.generate({ request, tools, stopWhen })
272
- })
273
-
274
- // Post-flight: catch ContextOverflow once, compact with overflow=true, retry once.
275
- let didRetry = false
276
- const response = yield* attempt().pipe(
277
- Effect.catchTag("LLM.Error", (err) => {
278
- if (err.reason._tag === "ContextOverflow" && compactionCfg.auto && !didRetry) {
279
- didRetry = true
280
- return Effect.gen(function* () {
281
- yield* compact({
282
- sessionId: session.id,
283
- store,
284
- model: config.model,
285
- keepRecent,
286
- overflow: true,
287
- })
288
- return yield* attempt()
378
+ const promptTokens = Math.ceil(input.prompt.length / 4)
379
+ const systemTokens = Math.ceil(resolvedSystemPrompt.length / 4)
380
+ if (estimateTokens(history) + promptTokens + systemTokens >= budget) {
381
+ yield* compact({
382
+ sessionId: session.id,
383
+ store,
384
+ model: config.model,
385
+ keepRecent,
386
+ overflow: false,
289
387
  })
290
388
  }
291
- return Effect.fail(err)
292
- }),
293
- )
294
- return response
295
- }),
296
- )
297
- return { text: result.text, usage: result.usage, events: result.events }
298
- }
299
-
300
- const toSSEHandler = (options?: SSEHandlerOptions) => makeSSEHandler(run, options)
301
-
302
- const sessions = makeSessionAPI({
303
- agentName: config.name,
304
- store,
305
- runtime: config.runtime,
306
- })
307
-
308
- const toHTTPHandlers = (options?: ToHTTPHandlersOptions): HTTPHandlers =>
309
- makeHTTPHandlers({
310
- api: sessions,
311
- run: (input) => run({ prompt: input.prompt, sessionId: input.sessionId, attachments: input.attachments }),
312
- authorize: options?.authorize,
313
- defaultFormat: options?.defaultFormat,
389
+ }
390
+
391
+ const attempt = () =>
392
+ Effect.gen(function* () {
393
+ const history = yield* store.getMessages(session.id)
394
+ const userContent: Array<
395
+ | { type: "text"; text: string }
396
+ | { type: "media"; mediaType: string; data: string; filename?: string }
397
+ > = []
398
+ if (input.prompt.length > 0) userContent.push({ type: "text", text: input.prompt })
399
+ for (const a of input.attachments ?? [])
400
+ userContent.push({
401
+ type: "media",
402
+ mediaType: a.mediaType,
403
+ data: a.url ?? a.data ?? "",
404
+ filename: a.filename,
405
+ })
406
+ const userMsg =
407
+ userContent.length === 0 ? LLM.user(input.prompt) : LLM.user(userContent)
408
+ const request = LLM.request({
409
+ model: config.model,
410
+ system: resolvedSystemPrompt,
411
+ messages: [...historyToLLMMessages([...history]), userMsg],
412
+ generation: config.generation,
413
+ })
414
+ return yield* LLMClient.generate({ request, tools, stopWhen })
415
+ })
416
+
417
+ // Post-flight: catch ContextOverflow once, compact with overflow=true, retry once.
418
+ let didRetry = false
419
+ const response = yield* attempt().pipe(
420
+ Effect.catchTag("LLM.Error", (err) => {
421
+ if (err.reason._tag === "ContextOverflow" && compactionCfg.auto && !didRetry) {
422
+ didRetry = true
423
+ return Effect.gen(function* () {
424
+ yield* compact({
425
+ sessionId: session.id,
426
+ store,
427
+ model: config.model,
428
+ keepRecent,
429
+ overflow: true,
430
+ })
431
+ return yield* attempt()
432
+ })
433
+ }
434
+ return Effect.fail(err)
435
+ }),
436
+ )
437
+ return response
438
+ }),
439
+ )
440
+ return { text: result.text, usage: result.usage, events: result.events }
441
+ }
442
+
443
+ const toSSEHandler = (options?: SSEHandlerOptions) => makeSSEHandler(run, options)
444
+
445
+ const sessions = makeSessionAPI({
446
+ agentName: config.name,
447
+ store,
448
+ runtime: config.runtime,
314
449
  })
315
-
316
- return { name: config.name, run, runOnce, toSSEHandler, sessions, toHTTPHandlers }
317
- }
450
+
451
+ const toHTTPHandlers = (options?: ToHTTPHandlersOptions): HTTPHandlers =>
452
+ makeHTTPHandlers({
453
+ api: sessions,
454
+ run: (input) =>
455
+ run({ prompt: input.prompt, sessionId: input.sessionId, attachments: input.attachments }),
456
+ authorize: options?.authorize,
457
+ defaultFormat: options?.defaultFormat,
458
+ })
459
+
460
+ return {
461
+ name: config.name,
462
+ run,
463
+ runOnce,
464
+ resolveApproval,
465
+ resume,
466
+ toSSEHandler,
467
+ sessions,
468
+ toHTTPHandlers,
469
+ }
470
+ }
package/src/events.ts CHANGED
@@ -36,6 +36,20 @@ export type ToolErrorEvent = {
36
36
  readonly id: string
37
37
  readonly name: string
38
38
  readonly message: string
39
+ /** Optional structured payload (e.g. tool-interrupt metadata). */
40
+ readonly metadata?: Record<string, unknown>
41
+ }
42
+
43
+ /**
44
+ * Emitted when a tool with permission rule `"ask"` (interrupt mode) is
45
+ * intercepted before execution. Host UIs should render an approve/reject
46
+ * control and later call `agent.resolveApproval` + `agent.resume`.
47
+ */
48
+ export type ToolApprovalRequestEvent = {
49
+ readonly type: "tool-approval-request"
50
+ readonly id: string
51
+ readonly name: string
52
+ readonly input: unknown
39
53
  }
40
54
 
41
55
  export type StepFinishEvent = {
@@ -137,6 +151,7 @@ export type AgentEvent =
137
151
  | ToolCallEvent
138
152
  | ToolResultEvent
139
153
  | ToolErrorEvent
154
+ | ToolApprovalRequestEvent
140
155
  | StepFinishEvent
141
156
  | FinishEvent
142
157
  | ErrorEvent
@@ -144,6 +159,9 @@ export type AgentEvent =
144
159
  | ContextCondenseEvent
145
160
  | ContextCondenseErrorEvent
146
161
 
162
+ /** Finish reason used when the turn stops waiting for user tool approval. */
163
+ export const FINISH_REASON_APPROVAL_REQUIRED = "approval-required" as const
164
+
147
165
  export const fromLLMEvent = (event: LLMEvent): AgentEvent | undefined => {
148
166
  if (event.type === "text-delta") return { type: "text-delta", id: event.id, text: event.text }
149
167
  if (event.type === "text-end") return { type: "text-end", id: event.id }
@@ -152,7 +170,13 @@ export const fromLLMEvent = (event: LLMEvent): AgentEvent | undefined => {
152
170
  if (event.type === "tool-result")
153
171
  return { type: "tool-result", id: event.id, name: event.name, result: event.result.value }
154
172
  if (event.type === "tool-error")
155
- return { type: "tool-error", id: event.id, name: event.name, message: event.message }
173
+ return {
174
+ type: "tool-error",
175
+ id: event.id,
176
+ name: event.name,
177
+ message: event.message,
178
+ metadata: event.metadata,
179
+ }
156
180
  if (event.type === "step-finish")
157
181
  return { type: "step-finish", index: event.index, reason: event.reason, usage: event.usage }
158
182
  if (event.type === "request-finish") return { type: "finish", reason: event.reason, usage: event.usage }
package/src/index.ts CHANGED
@@ -6,6 +6,9 @@ export {
6
6
  type Agent,
7
7
  type DefineAgentConfig,
8
8
  type RunInput,
9
+ type ResumeInput,
10
+ type ResolveApprovalInput,
11
+ type ResolveApprovalResult,
9
12
  type RunOnceResult,
10
13
  type ToHTTPHandlersOptions,
11
14
  } from "./agent"
@@ -74,11 +77,12 @@ export type {
74
77
  ToolCallEvent,
75
78
  ToolResultEvent,
76
79
  ToolErrorEvent,
80
+ ToolApprovalRequestEvent,
77
81
  StepFinishEvent,
78
82
  FinishEvent,
79
83
  ErrorEvent,
80
84
  } from "./events"
81
- export { fromLLMEvent } from "./events"
85
+ export { fromLLMEvent, FINISH_REASON_APPROVAL_REQUIRED } from "./events"
82
86
 
83
87
  // Transcript helpers — consumer-side fallback for persisting display_response turns
84
88
  export {
@@ -104,7 +108,11 @@ export { makeSSEHandler, writeEventsToResponse, type SSEFormat, type SSEHandlerO
104
108
  export {
105
109
  applyPermission,
106
110
  resolveRule,
111
+ isToolInterruptMetadata,
112
+ toolInterruptFailure,
113
+ TOOL_INTERRUPT_KIND,
107
114
  type PermissionAskHandler,
115
+ type PermissionAskMode,
108
116
  type PermissionAskRequest,
109
117
  type PermissionConfig,
110
118
  type PermissionRule,
package/src/mcp/client.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  import { Client } from "@modelcontextprotocol/sdk/client/index.js"
4
4
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
5
5
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
6
- import { Effect, Schema } from "effect"
6
+ import { Effect } from "effect"
7
7
  import { Tool, ToolFailure } from "@tinyweb-agent-framework/llm"
8
8
 
9
9
  // ---------------------------------------------------------------------------
@@ -39,26 +39,45 @@ export type McpClient = {
39
39
  // Helpers
40
40
  // ---------------------------------------------------------------------------
41
41
 
42
- const jsonSchema = Schema.Record(Schema.String, Schema.Unknown)
42
+ /**
43
+ * MCP tools ship a real JSON Schema (`inputSchema`). We must pass it through
44
+ * `Tool.make({ jsonSchema })` so the LLM sees required fields (e.g. Perplexity
45
+ * `messages[]` / `query`). Using a generic Record schema loses that shape and
46
+ * the model invents empty `{}` args → server-side validation errors.
47
+ */
48
+ function asJsonSchema(inputSchema: unknown): Record<string, unknown> {
49
+ if (inputSchema && typeof inputSchema === "object" && !Array.isArray(inputSchema)) {
50
+ return inputSchema as Record<string, unknown>
51
+ }
52
+ return { type: "object", properties: {} }
53
+ }
43
54
 
44
- function buildTool(serverName: string, mcpTool: { name: string; description?: string; inputSchema: unknown }, client: Client): Tool.AnyExecutableTool {
55
+ function buildTool(
56
+ serverName: string,
57
+ mcpTool: { name: string; description?: string; inputSchema: unknown },
58
+ client: Client,
59
+ ): Tool.AnyExecutableTool {
45
60
  const toolName = `${serverName}__${mcpTool.name}`
46
- const parameters = (mcpTool.inputSchema ?? { type: "object", properties: {} }) as Record<string, unknown>
61
+ const jsonSchema = asJsonSchema(mcpTool.inputSchema)
47
62
 
48
63
  return Tool.make({
49
64
  description: mcpTool.description ?? toolName,
50
- parameters: jsonSchema,
51
- success: Schema.Unknown,
65
+ // Dynamic mode — preserves MCP inputSchema on the wire for the LLM.
66
+ jsonSchema: jsonSchema as never,
52
67
  execute: (input) =>
53
68
  Effect.tryPromise({
54
69
  try: async () => {
55
- const result = await client.callTool({ name: mcpTool.name, arguments: input as Record<string, unknown> })
70
+ const args =
71
+ input && typeof input === "object" && !Array.isArray(input)
72
+ ? (input as Record<string, unknown>)
73
+ : {}
74
+ const result = await client.callTool({ name: mcpTool.name, arguments: args })
56
75
  // MCP callTool returns {content: [{type, text?}], isError?}
76
+ const parts = (result.content as { type: string; text?: string }[] | undefined) ?? []
77
+ const text = parts.map((c) => c.text ?? "").join("\n")
57
78
  if (result.isError) {
58
- const text = (result.content as { type: string; text?: string }[]).map((c) => c.text ?? "").join("\n")
59
79
  throw new Error(text || "MCP tool returned error")
60
80
  }
61
- const text = (result.content as { type: string; text?: string }[]).map((c) => c.text ?? "").join("\n")
62
81
  return text
63
82
  },
64
83
  catch: (err) => new ToolFailure({ message: String(err) }),