@agentproto/tool 0.2.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -93,7 +93,8 @@ var constructTool = createDoctype({
93
93
  metadata: Object.freeze({ ...def.metadata ?? {} }),
94
94
  idempotent: def.idempotent ?? false,
95
95
  defaultImplementation: def.defaultImplementation,
96
- driverConstraints: freezeProviderConstraints(def.driverConstraints)
96
+ driverConstraints: freezeProviderConstraints(def.driverConstraints),
97
+ transformers: def.transformers ? Object.freeze([...def.transformers]) : void 0
97
98
  };
98
99
  }
99
100
  });
@@ -315,5 +316,5 @@ function toolFromManifest(args) {
315
316
  }
316
317
 
317
318
  export { ToolError, defineTool, parseToolManifest, toToolError, toToolResult, toolFromManifest, toolFromManifestOnly, toolManifestFrontmatterSchema, validateContext, validateInput, validateOutput };
318
- //# sourceMappingURL=chunk-VCLSUUB5.mjs.map
319
- //# sourceMappingURL=chunk-VCLSUUB5.mjs.map
319
+ //# sourceMappingURL=chunk-7UKT5ZEH.mjs.map
320
+ //# sourceMappingURL=chunk-7UKT5ZEH.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/define-tool.ts","../src/manifest/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AA6BO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACA,SAAA;AAAA,EACA,KAAA;AAAA,EAET,YAAY,OAAA,EAA2B;AACrC,IAAA,KAAA,CAAM,QAAQ,OAAO,CAAA;AACrB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,KAAA;AACtC,IAAA,IAAA,CAAK,QAAQ,OAAA,CAAQ,KAAA;AAAA,EACvB;AAAA,EAEA,MAAA,GAA2B;AACzB,IAAA,OAAO;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. Tool-specific codes MAY use a domain\n * prefix (`\"stripe:card_declined\"`).\n */\nexport type ToolErrorCode =\n | \"input_invalid\"\n | \"output_invalid\"\n | \"unauthorised\"\n | \"not_found\"\n | \"rate_limited\"\n | \"timeout\"\n | \"upstream_error\"\n | \"internal\"\n | (string & {})\n\nexport interface ToolErrorPayload {\n code: ToolErrorCode\n message: string\n retryable?: boolean\n cause?: unknown\n}\n\n/**\n * Structured error thrown by tool bodies. Adapters wrap this into the\n * standard {@link ToolResult} envelope; bodies MUST throw it (never\n * return error objects).\n */\nexport class ToolError extends Error {\n readonly code: ToolErrorCode\n readonly retryable: boolean\n readonly cause: unknown\n\n constructor(payload: ToolErrorPayload) {\n super(payload.message)\n this.name = \"ToolError\"\n this.code = payload.code\n this.retryable = payload.retryable ?? false\n this.cause = payload.cause\n }\n\n toJSON(): ToolErrorPayload {\n return {\n code: this.code,\n message: this.message,\n retryable: this.retryable,\n ...(this.cause !== undefined ? { cause: this.cause } : {}),\n }\n }\n}\n\n/**\n * Wrap an unknown thrown value into a {@link ToolError}. Used by adapters\n * to normalise non-ToolError throws into the standard envelope.\n */\nexport function toToolError(thrown: unknown): ToolError {\n if (thrown instanceof ToolError) return thrown\n if (thrown instanceof Error) {\n return new ToolError({\n code: \"internal\",\n message: thrown.message,\n cause: thrown,\n })\n }\n return new ToolError({\n code: \"internal\",\n message: String(thrown),\n cause: thrown,\n })\n}\n\n/**\n * Adapter helper: project a thrown ToolError (or any throw) into the\n * standard {@link ToolResult} envelope. Adapters MUST do this; bodies MUST NOT.\n */\nexport function toToolResult<T>(\n value: T | undefined,\n thrown: unknown\n): ToolResult<T> {\n if (thrown !== undefined) {\n const err = toToolError(thrown)\n return { ok: false, error: err.toJSON() }\n }\n return { ok: true, value: value as T }\n}\n","import { createDoctype } from \"@agentproto/define-doctype\"\nimport Ajv from \"ajv\"\nimport type { ZodType } from \"zod\"\nimport { ToolError } from \"./errors.js\"\nimport type {\n ApprovalClass,\n DriverConstraints,\n DriverKind,\n ToolCapabilities,\n ToolContext,\n ToolDefinition,\n ToolHandle,\n ValidationResult,\n} from \"./types.js\"\n\nconst PROVIDER_KINDS: readonly DriverKind[] = [\n \"cli\",\n \"http\",\n \"mcp\",\n \"sdk\",\n \"builtin\",\n]\n\n/**\n * AIP-14 reference implementation of `defineTool`.\n *\n * Returns a {@link ToolHandle} with defaults applied. The handle is a\n * pure contract — schemas, governance metadata, provider routing\n * hints. Bodies live on AIP-30 PROVIDER manifests; invocation goes\n * through provider-runtime's resolver.\n *\n * Built on `createDoctype` from `@agentproto/define-doctype`: the\n * id-pattern + description-length validation and the top-level\n * `Object.freeze` are shared with every other AIP defineX. The\n * spec-14-specific parts (migration guard for `execute`, defaulting\n * `approval` from `mutates`, freezing nested arrays/objects) live in\n * `validate` and `build` below.\n *\n * Conformance highlights ([§ Conformance rules](https://agentproto.sh/docs/aip-14)):\n * - No `execute` field on the contract — bodies are providers' job.\n * - `defineTool` MUST refuse a definition carrying `execute` (migration error).\n * - No I/O at module load — `defineTool(...)` is pure construction.\n */\nconst constructTool = createDoctype<\n ToolDefinition<unknown, unknown, ToolContext>,\n ToolHandle<unknown, unknown, ToolContext>\n>({\n aip: 14,\n name: \"tool\",\n validate(def) {\n // Migration guard: catch authors trying to ship a body on the contract.\n // The body lives on a PROVIDER (per AIP-30); reject at construction.\n if (\"execute\" in (def as unknown as Record<string, unknown>)) {\n throw new Error(\n `defineTool: id='${def.id}' carries an 'execute' property. ` +\n `Bodies live on AIP-30 PROVIDER manifests, not on the TOOL contract. ` +\n `See https://agentproto.sh/docs/aip-30 for migration.`,\n )\n }\n },\n build(def) {\n return {\n id: def.id,\n name: def.name ?? def.id,\n description: def.description,\n version: def.version,\n inputSchema: def.inputSchema,\n outputSchema: def.outputSchema,\n inputs: def.inputs ? Object.freeze({ ...def.inputs }) : undefined,\n outputs: def.outputs ? Object.freeze({ ...def.outputs }) : undefined,\n contextSchema: def.contextSchema,\n mutates: Object.freeze([...(def.mutates ?? [])]),\n requires: freezeCapabilities(def.requires),\n approval: defaultApproval(def.approval, def.mutates),\n riskLevel: def.riskLevel ?? 0,\n costClass: def.costClass ?? \"trivial\",\n timeoutMs: def.timeoutMs ?? 30_000,\n retry: def.retry,\n tags: Object.freeze([...(def.tags ?? [])]),\n metadata: Object.freeze({ ...(def.metadata ?? {}) }),\n idempotent: def.idempotent ?? false,\n defaultImplementation: def.defaultImplementation,\n driverConstraints: freezeProviderConstraints(def.driverConstraints),\n transformers: def.transformers\n ? Object.freeze([...def.transformers])\n : undefined,\n }\n },\n})\n\n/**\n * Public-facing `defineTool` — typed wrapper around `constructTool`\n * that preserves the per-call `<TInput, TOutput, TContext>` inference\n * so callers don't write any generics. The wrapper exists purely for\n * generic propagation; the runtime body is the meta-factory above.\n */\nexport function defineTool<\n TInput,\n TOutput,\n TContext extends ToolContext = ToolContext,\n>(\n definition: ToolDefinition<TInput, TOutput, TContext>,\n): ToolHandle<TInput, TOutput, TContext> {\n return constructTool(\n definition as ToolDefinition<unknown, unknown, ToolContext>,\n ) as unknown as ToolHandle<TInput, TOutput, TContext>\n}\n\n/**\n * Validate input against a tool's `inputSchema`. Returns a typed\n * {@link ValidationResult}; provider runtimes MUST call this BEFORE\n * dispatching to the provider's body.\n *\n * Priority:\n * 1. zod `inputSchema` (v0.1) — used when present.\n * 2. JSON Schema `inputs` (v0.2) — fallback for manifest-only tools.\n * 3. No schema — passthrough (returns `ok: true`).\n */\nexport function validateInput<TInput>(\n handle: Pick<ToolHandle<TInput>, \"id\" | \"inputSchema\" | \"inputs\">,\n input: unknown,\n): ValidationResult<TInput> {\n if (handle.inputSchema) {\n const result = handle.inputSchema.safeParse(input)\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"input_invalid\",\n message: `id='${handle.id}': ${formatZodIssues(result.error.issues)}`,\n cause: result.error.issues,\n },\n }\n }\n return { ok: true, value: result.data as TInput }\n }\n if (handle.inputs) {\n return validateJsonSchema<TInput>(handle.id, handle.inputs, input)\n }\n return { ok: true, value: input as TInput }\n}\n\n/**\n * Validate context against a tool's `contextSchema` (when declared).\n * Returns a typed {@link ValidationResult}; provider runtimes MUST\n * call this BEFORE dispatching when the contract has a contextSchema.\n *\n * Tools without a contextSchema accept any context shape; this helper\n * returns the input verbatim in that case.\n *\n * Context validation uses only zod (no JSON Schema fallback) — context\n * schemas are always authored in TS, never in manifests.\n */\nexport function validateContext<TContext extends ToolContext = ToolContext>(\n handle: Pick<ToolHandle<unknown, unknown, TContext>, \"id\" | \"contextSchema\">,\n context: unknown,\n): ValidationResult<TContext> {\n if (!handle.contextSchema) {\n return { ok: true, value: context as TContext }\n }\n const result = handle.contextSchema.safeParse(context)\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"input_invalid\",\n message: `id='${handle.id}': context does not match contextSchema — ${formatZodIssues(result.error.issues)}`,\n field: \"context\",\n cause: result.error.issues,\n },\n }\n }\n return { ok: true, value: result.data as TContext }\n}\n\n/**\n * Validate output against a tool's `outputSchema`. Returns the typed\n * value on success; throws {@link ToolError} with code `\"output_invalid\"`\n * on contract violation.\n *\n * Priority:\n * 1. zod `outputSchema` (v0.1) — used when present.\n * 2. JSON Schema `outputs` (v0.2) — fallback for manifest-only tools.\n * 3. No schema — passthrough (returns the value as-is).\n */\nexport function validateOutput<TOutput>(\n handle: Pick<ToolHandle<unknown, TOutput>, \"id\" | \"outputSchema\" | \"outputs\">,\n output: unknown,\n): TOutput {\n if (handle.outputSchema) {\n const result = handle.outputSchema.safeParse(output)\n if (!result.success) {\n throw new ToolError({\n code: \"output_invalid\",\n message: `id='${handle.id}': provider produced output that does not match outputSchema — ${formatZodIssues(result.error.issues)}`,\n cause: result.error.issues,\n })\n }\n return result.data as TOutput\n }\n if (handle.outputs) {\n const result = validateJsonSchema<TOutput>(handle.id, handle.outputs, output)\n if (!result.ok) {\n throw new ToolError({\n code: \"output_invalid\",\n message: result.error.message,\n cause: result.error.cause,\n })\n }\n return result.value\n }\n return output as TOutput\n}\n\nfunction defaultApproval(\n declared: ApprovalClass | undefined,\n mutates: readonly string[] | undefined,\n): ApprovalClass {\n if (declared) return declared\n return mutates && mutates.length > 0 ? \"on-mutate\" : \"auto\"\n}\n\nfunction freezeCapabilities(\n caps: ToolCapabilities | undefined,\n): Readonly<ToolCapabilities> {\n return Object.freeze({\n network: Object.freeze([...(caps?.network ?? [])]),\n secrets: Object.freeze([...(caps?.secrets ?? [])]),\n tools: Object.freeze([...(caps?.tools ?? [])]),\n })\n}\n\nfunction freezeProviderConstraints(\n c: DriverConstraints | undefined,\n): Required<DriverConstraints> {\n const forbid = (c?.forbid ?? []).filter((k): k is DriverKind =>\n PROVIDER_KINDS.includes(k as DriverKind),\n )\n const requireKind = (c?.requireKind ?? []).filter((k): k is DriverKind =>\n PROVIDER_KINDS.includes(k as DriverKind),\n )\n return Object.freeze({\n forbid: Object.freeze(forbid) as readonly DriverKind[],\n requireKind: Object.freeze(requireKind) as readonly DriverKind[],\n })\n}\n\nfunction formatZodIssues(\n issues: ReadonlyArray<{ path: ReadonlyArray<PropertyKey>; message: string }>,\n): string {\n return issues\n .map((i) => `${i.path.length > 0 ? i.path.join(\".\") + \": \" : \"\"}${i.message}`)\n .join(\"; \")\n}\n\n// Shared Ajv instance — created once at module load.\n// allErrors: true so we surface all violations, not just the first.\nconst _ajv = new Ajv({ allErrors: true })\n\n// Validator cache keyed by schema object identity. Avoids repeated _ajv.compile()\n// calls (which go through Ajv's internal registry) and lets GC collect validators\n// when a tool handle is no longer referenced.\nconst _validatorCache = new WeakMap<\n object,\n ReturnType<typeof _ajv.compile>\n>()\n\nfunction validateJsonSchema<T>(\n toolId: string,\n schema: Record<string, unknown>,\n value: unknown,\n): ValidationResult<T> {\n let validate = _validatorCache.get(schema)\n if (!validate) {\n validate = _ajv.compile(schema as Parameters<typeof _ajv.compile>[0])\n _validatorCache.set(schema, validate)\n }\n const valid = validate(value)\n if (!valid) {\n const errors = validate.errors ?? []\n const message = errors\n .map((e) => `${e.instancePath || \"/\"} ${e.message}`)\n .join(\"; \")\n return {\n ok: false,\n error: {\n code: \"input_invalid\",\n message: `id='${toolId}': ${message}`,\n cause: errors,\n },\n }\n }\n return { ok: true, value: value as T }\n}\n\nexport type { ZodType }\n","import matter from \"gray-matter\"\nimport { z, type ZodType } from \"zod\"\nimport { defineTool } from \"../define-tool.js\"\nimport type { ApprovalClass, ToolContext, ToolHandle } from \"../types.js\"\n\n/**\n * AIP-14 TOOL.md sidecar parser.\n *\n * Reads frontmatter (host-relevant metadata) + body (long-form\n * description / examples / errors). The TS module's `defineTool(...)`\n * supplies the schemas and execute body; this manifest supplies the\n * runtime metadata that overrides or augments the in-code defaults.\n *\n * Field set covers AIP-14 §\"Frontmatter\" — required and optional fields\n * normalised to snake_case → camelCase.\n */\n\nexport const toolManifestFrontmatterSchema = z.object({\n schema: z.literal(\"agentproto/tool/v1\").optional(),\n name: z.string().min(1).max(80),\n id: z.string().regex(/^[a-z][a-z0-9._-]{1,63}$/),\n description: z.string().min(1).max(2000),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+/),\n\n // Optional metadata\n mutates: z.array(z.string()).optional(),\n requires: z\n .object({\n network: z.array(z.string()).optional(),\n secrets: z.array(z.string()).optional(),\n tools: z.array(z.string()).optional(),\n })\n .optional(),\n // `ApprovalClass` is `\"auto\" | \"always\" | \"on-mutate\" | \\`policy:${string}\\``.\n // z.union widens the regex branch to plain `string` (zod can't express\n // template literal types), so we use `z.custom` to keep the inferred\n // type exact — matters because `defineTool` accepts `ApprovalClass`.\n approval: z\n .custom<ApprovalClass>(\n (v): v is ApprovalClass =>\n typeof v === \"string\" &&\n (v === \"auto\" ||\n v === \"always\" ||\n v === \"on-mutate\" ||\n /^policy:/.test(v)),\n { message: \"expected 'auto' | 'always' | 'on-mutate' | 'policy:<name>'\" },\n )\n .optional(),\n risk_level: z\n .union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)])\n .optional(),\n cost_class: z.enum([\"trivial\", \"metered\", \"expensive\"]).optional(),\n timeout_ms: z.number().int().positive().optional(),\n idempotent: z.boolean().optional(),\n tags: z.array(z.string()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n\n // AIP-16 IO blocks — `inputs`/`outputs` as JSON Schema objects. Kept\n // structurally loose here (validated as objects, not deep-checked against\n // the AIP-16 meta-schema); preserved so a manifest's declared IO contract\n // survives the parse → handle round-trip instead of being silently dropped.\n inputs: z.record(z.string(), z.unknown()).optional(),\n outputs: z.record(z.string(), z.unknown()).optional(),\n\n // AIP-26 / AIP-17 / AIP-19 references — kept loose; validated by their\n // respective AIPs' adapters when consumed.\n code: z.unknown().optional(),\n run: z.unknown().optional(),\n runner: z.unknown().optional(),\n secrets: z.unknown().optional(),\n network: z.unknown().optional(),\n})\n\nexport type ToolManifestFrontmatter = z.infer<\n typeof toolManifestFrontmatterSchema\n>\n\nexport interface ToolManifest {\n frontmatter: ToolManifestFrontmatter\n body: string\n}\n\n/**\n * Parse a TOOL.md source string into structured frontmatter + body.\n * Throws on missing frontmatter or schema-invalid frontmatter.\n */\nexport function parseToolManifest(source: string): ToolManifest {\n const parsed = matter(source)\n if (Object.keys(parsed.data).length === 0) {\n throw new Error(\"parseToolManifest: missing or empty frontmatter\")\n }\n const result = toolManifestFrontmatterSchema.safeParse(parsed.data)\n if (!result.success) {\n throw new Error(\n `parseToolManifest: invalid frontmatter — ${result.error.issues\n .map(i => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`\n )\n }\n return { frontmatter: result.data, body: parsed.content }\n}\n\n/**\n * Build a {@link ToolHandle} from a manifest that has no companion TS module.\n *\n * `inputSchema`/`outputSchema` are omitted; IO validation falls back to the\n * AIP-16 `inputs`/`outputs` JSON Schema blocks declared in the frontmatter\n * (via `validateInput`/`validateOutput`). The returned handle is typed as\n * `ToolHandle<unknown, unknown>` since the generic shapes are not statically\n * known.\n *\n * Use this when loading an agent-generated TOOL.md whose IO contract is\n * expressed in YAML (`inputs:`/`outputs:`) rather than a compiled TS module.\n */\nexport function toolFromManifestOnly(\n manifest: ToolManifest,\n): ToolHandle<unknown, unknown> {\n const fm = manifest.frontmatter\n return defineTool({\n id: fm.id,\n name: fm.name,\n description: fm.description,\n version: fm.version,\n inputs: fm.inputs,\n outputs: fm.outputs,\n mutates: fm.mutates,\n requires: fm.requires,\n approval: fm.approval,\n riskLevel: fm.risk_level,\n costClass: fm.cost_class,\n timeoutMs: fm.timeout_ms,\n idempotent: fm.idempotent,\n tags: fm.tags,\n metadata: fm.metadata,\n })\n}\n\n/**\n * Build a fully-typed {@link ToolHandle} from a parsed `TOOL.md` manifest\n * + caller-supplied schemas. The .md is the single source of truth for\n * metadata (id, name, description, version, mutates, approval, …); the\n * schemas live in the TS module that ships alongside the .md.\n *\n * Both inputs are revalidated by `defineTool`'s shared invariants\n * (id pattern, description length, top-level freeze) — `parseToolManifest`\n * already enforces a stricter id pattern + version semver, so a\n * well-formed manifest passes through cleanly. Mismatches between the\n * manifest's id-shape and `defineTool`'s pattern surface a\n * descriptive error from the same validation pipeline as the TS path.\n *\n * @example\n * const manifest = parseToolManifest(readFileSync(\"./echo/TOOL.md\", \"utf8\"))\n * const echo = toolFromManifest({\n * manifest,\n * inputSchema: z.object({ msg: z.string() }),\n * outputSchema: z.object({ msg: z.string() }),\n * })\n */\nexport function toolFromManifest<\n TInput,\n TOutput,\n TContext extends ToolContext = ToolContext,\n>(args: {\n manifest: ToolManifest\n inputSchema: ZodType<TInput>\n outputSchema: ZodType<TOutput>\n contextSchema?: ZodType<TContext>\n}): ToolHandle<TInput, TOutput, TContext> {\n const fm = args.manifest.frontmatter\n return defineTool<TInput, TOutput, TContext>({\n id: fm.id,\n name: fm.name,\n description: fm.description,\n version: fm.version,\n inputSchema: args.inputSchema,\n outputSchema: args.outputSchema,\n inputs: fm.inputs,\n outputs: fm.outputs,\n contextSchema: args.contextSchema,\n mutates: fm.mutates,\n requires: fm.requires,\n approval: fm.approval,\n riskLevel: fm.risk_level,\n costClass: fm.cost_class,\n timeoutMs: fm.timeout_ms,\n idempotent: fm.idempotent,\n tags: fm.tags,\n metadata: fm.metadata,\n })\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { ZodType, z } from 'zod';
1
+ import { ZodType, ZodRawShape, z } from 'zod';
2
2
 
3
3
  /**
4
4
  * AIP-14 ToolDefinition — the abstract agent contract.
@@ -83,6 +83,11 @@ interface ToolDefinition<TInput = unknown, TOutput = unknown, TContext extends T
83
83
  * HTTP" (`forbid: ["http"]`) for self-hosted-only contracts.
84
84
  */
85
85
  driverConstraints?: DriverConstraints;
86
+ /**
87
+ * Cross-cutting concerns (see {@link ToolHandle.transformers}) carried on
88
+ * the contract and applied by MCP-facing adapters at registration.
89
+ */
90
+ transformers?: readonly ToolTransformer[];
86
91
  }
87
92
  type DriverKind = "cli" | "http" | "mcp" | "sdk" | "builtin";
88
93
  interface DriverConstraints {
@@ -138,6 +143,42 @@ interface ToolHandle<TInput = unknown, TOutput = unknown, TContext extends ToolC
138
143
  readonly idempotent: boolean;
139
144
  readonly defaultImplementation?: string;
140
145
  readonly driverConstraints: Required<DriverConstraints>;
146
+ /**
147
+ * Cross-cutting concerns applied by MCP-facing adapters (`toMcpTool`) at
148
+ * registration time — pagination, error normalization, … Listed
149
+ * outermost-first: `wrapHandler` folds so the FIRST declared transformer
150
+ * ends up the OUTERMOST wrapper around the base handler (e.g.
151
+ * `[catchErrors(), paginated(...)]` paginates around the body, then
152
+ * catchErrors around that).
153
+ */
154
+ readonly transformers?: readonly ToolTransformer[];
155
+ }
156
+ /**
157
+ * A composable cross-cutting concern applied to a TOOL's MCP projection.
158
+ *
159
+ * Two hooks:
160
+ * - `wrapShape` extends the declared zod raw shape with the transformer's
161
+ * own input params (applied in declared order).
162
+ * - `wrapHandler` wraps the handler pipeline (applied outermost-first —
163
+ * see {@link ToolHandle.transformers}). Unlike `wrapShape`, the wrapped
164
+ * pipeline may CHANGE the output type (`TNext`): concrete transformers
165
+ * typically terminate the pipeline by returning a pre-serialized MCP
166
+ * text result (`{ content: [{ type: "text", text }], isError? }`), which
167
+ * the MCP adapter passes through verbatim instead of JSON-stringifying.
168
+ *
169
+ * Composition order: transformers compose LEFT-TO-RIGHT in declared order —
170
+ * the first transformer listed is the outermost wrapper. E.g.
171
+ * `[catchErrors(), paginated(...)]` runs paginate around the base handler,
172
+ * then catchErrors around that, so even a pagination failure is caught.
173
+ */
174
+ interface ToolTransformer<TInput = unknown, TOutput = unknown, TNext = TOutput> {
175
+ /** Diagnostic name (surfaced in registration errors / audits). */
176
+ name: string;
177
+ /** Extend the declared input shape with this transformer's params. */
178
+ wrapShape?: (shape: ZodRawShape) => ZodRawShape;
179
+ /** Wrap the handler pipeline. (Method syntax: keeps heterogeneous
180
+ * transformer generics assignable to `ToolTransformer[]`.) */
181
+ wrapHandler(handler: (input: TInput) => Promise<TOutput>): (input: TInput) => Promise<TNext>;
141
182
  }
142
183
  /**
143
184
  * Standard out-of-band result envelope. Provider runtimes wrap thrown
@@ -271,4 +312,4 @@ declare function toolFromManifest<TInput, TOutput, TContext extends ToolContext
271
312
  contextSchema?: ZodType<TContext>;
272
313
  }): ToolHandle<TInput, TOutput, TContext>;
273
314
 
274
- export { type ApprovalClass as A, type DriverConstraints as D, type RetryPolicy as R, type ToolContext as T, type ValidationResult as V, type ToolDefinition as a, type ToolHandle as b, type ToolResult as c, type DriverKind as d, type ToolCapabilities as e, type ToolManifest as f, type ToolManifestFrontmatter as g, type ValidationFailure as h, type ValidationSuccess as i, toolFromManifestOnly as j, toolManifestFrontmatterSchema as k, parseToolManifest as p, toolFromManifest as t };
315
+ export { type ApprovalClass as A, type DriverConstraints as D, type RetryPolicy as R, type ToolContext as T, type ValidationResult as V, type ToolDefinition as a, type ToolHandle as b, type ToolResult as c, type ToolTransformer as d, type DriverKind as e, type ToolCapabilities as f, type ToolManifest as g, type ToolManifestFrontmatter as h, type ValidationFailure as i, type ValidationSuccess as j, toolFromManifestOnly as k, toolManifestFrontmatterSchema as l, parseToolManifest as p, toolFromManifest as t };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { T as ToolContext, a as ToolDefinition, b as ToolHandle, V as ValidationResult, c as ToolResult } from './index-63aR8ryG.js';
2
- export { A as ApprovalClass, D as DriverConstraints, d as DriverKind, R as RetryPolicy, e as ToolCapabilities, f as ToolManifest, g as ToolManifestFrontmatter, h as ValidationFailure, i as ValidationSuccess, p as parseToolManifest, t as toolFromManifest, j as toolFromManifestOnly } from './index-63aR8ryG.js';
1
+ import { T as ToolContext, a as ToolDefinition, b as ToolHandle, V as ValidationResult, c as ToolResult, d as ToolTransformer } from './index-DpcQ_sMe.js';
2
+ export { A as ApprovalClass, D as DriverConstraints, e as DriverKind, R as RetryPolicy, f as ToolCapabilities, g as ToolManifest, h as ToolManifestFrontmatter, i as ValidationFailure, j as ValidationSuccess, p as parseToolManifest, t as toolFromManifest, k as toolFromManifestOnly } from './index-DpcQ_sMe.js';
3
3
  import * as _agentproto_manifest from '@agentproto/manifest';
4
4
  import { DoctypeSpec } from '@agentproto/manifest';
5
- import 'zod';
5
+ import { z } from 'zod';
6
6
 
7
7
  /**
8
8
  * Public-facing `defineTool` — typed wrapper around `constructTool`
@@ -120,6 +120,114 @@ declare function toToolError(thrown: unknown): ToolError;
120
120
  */
121
121
  declare function toToolResult<T>(value: T | undefined, thrown: unknown): ToolResult<T>;
122
122
 
123
+ /**
124
+ * Concrete {@link ToolTransformer}s — cross-cutting concerns composed by
125
+ * MCP-facing adapters (`toMcpTool`) around a tool's handler pipeline.
126
+ */
127
+ /** The MCP text-result shape transformers terminate the pipeline into. */
128
+ interface McpTextResult {
129
+ content: Array<{
130
+ type: "text";
131
+ text: string;
132
+ }>;
133
+ isError?: boolean;
134
+ }
135
+ interface PaginatedOptions<TItem> {
136
+ /**
137
+ * REQUIRED per-item compact projection. Requiring it is the point: there
138
+ * is no code path that accepts the `compact` param without an actual
139
+ * compact projection behind it, killing the "declared but dead param"
140
+ * bug class. Pass the identity function only if you truly want
141
+ * `compact` to be a no-op.
142
+ */
143
+ project: (item: TItem) => object;
144
+ /** Key function for the opaque pagination cursor. */
145
+ keyOf?: (item: TItem) => string | number | null;
146
+ /** Hard ceiling on `limit` (default 200 — matches the daemon tools). */
147
+ maxLimit?: number;
148
+ /**
149
+ * Wrapper key for the NON-paginated output. With no `limit`/`cursor`,
150
+ * legacy list tools returned `{ sessions: [...] }` rather than the page
151
+ * envelope; set this to reproduce that wrapper (default `"items"`).
152
+ */
153
+ itemKey?: string;
154
+ }
155
+ /**
156
+ * Pagination transformer — adds {@link pageParamsShape} to the input shape
157
+ * and wraps the handler (which must return the FULL, unprojected item
158
+ * array) with the shared cursor/limit semantics:
159
+ *
160
+ * - `limit`/`cursor` present → the `{ items, nextCursor?, total }` page
161
+ * envelope via `paginate` + `toolText` (cursor/limit semantics are the
162
+ * exact ones the daemon's list tools already depend on).
163
+ * - neither present → the legacy `{ [itemKey]: [...] }` wrapper, no
164
+ * envelope fields.
165
+ *
166
+ * Rows are COMPACT by default (`project`); `full: true` / `compact: false`
167
+ * returns the unprojected records. `fields` is a per-item allowlist
168
+ * applied on the paginated envelope branch (matching existing behavior).
169
+ */
170
+ declare function paginated<TItem extends object>(opts: PaginatedOptions<TItem>): ToolTransformer<unknown, readonly TItem[], McpTextResult>;
171
+ /**
172
+ * Error-normalization transformer — wraps the handler so ANY thrown error
173
+ * becomes the single canonical MCP error result
174
+ * `{ content: [{ type: "text", text: <message> }], isError: true }`,
175
+ * replacing the ~150 copy-pasted inline catch blocks.
176
+ */
177
+ declare function catchErrors(): ToolTransformer<unknown, unknown, McpTextResult>;
178
+
179
+ /**
180
+ * Shared pagination primitives (moved here from `@agentproto/runtime`'s
181
+ * `tool-envelope.ts` so the `paginated()` ToolTransformer can reuse the
182
+ * exact cursor/limit semantics the daemon's list tools already depend on).
183
+ * `@agentproto/runtime` re-exports this module verbatim, so existing
184
+ * imports are unchanged.
185
+ */
186
+ /** Shared pagination params, spread into every list tool's input schema. */
187
+ interface PageParams {
188
+ limit?: number;
189
+ cursor?: string;
190
+ since?: number;
191
+ compact?: boolean;
192
+ full?: boolean;
193
+ fields?: string[];
194
+ }
195
+ interface Page<T> {
196
+ items: T[];
197
+ nextCursor?: string;
198
+ total?: number;
199
+ truncated?: boolean;
200
+ }
201
+ /** Opaque cursor: base64(JSON `{ k: keysetValue, i: index }`). */
202
+ interface CursorPayload {
203
+ k: string | number | null;
204
+ i: number;
205
+ }
206
+ declare function encodeCursor(payload: CursorPayload): string;
207
+ /** No `unknown`/`as`: the JSON boundary is typed by zod's safeParse/parse. */
208
+ declare function decodeCursor(token: string): CursorPayload | null;
209
+ interface PaginateOpts<T> {
210
+ maxLimit: number;
211
+ keyOf?: (item: T) => string | number | null;
212
+ }
213
+ declare function paginate<T>(items: readonly T[], params: PageParams, opts: PaginateOpts<T>): Page<T>;
214
+ /**
215
+ * Compact serializer — replaces every `JSON.stringify(x, null, 2)` in list handlers.
216
+ *
217
+ * When `params.fields` is supplied, an explicit allowlist is applied to every
218
+ * item (mechanically, across all call sites): items keep only the named keys.
219
+ * Absent `fields`, the output is byte-identical to `JSON.stringify(page)`.
220
+ */
221
+ declare function toolText<T extends object>(page: Page<T>, params?: Pick<PageParams, "fields">): string;
222
+ /** Zod fragment to spread into each list tool's input schema. */
223
+ declare const pageParamsShape: {
224
+ readonly limit: z.ZodOptional<z.ZodNumber>;
225
+ readonly cursor: z.ZodOptional<z.ZodString>;
226
+ readonly compact: z.ZodOptional<z.ZodBoolean>;
227
+ readonly full: z.ZodOptional<z.ZodBoolean>;
228
+ readonly fields: z.ZodOptional<z.ZodArray<z.ZodString>>;
229
+ };
230
+
123
231
  /**
124
232
  * @agentproto/tool — AIP-14 TOOL.md `defineTool` reference impl.
125
233
  *
@@ -134,4 +242,4 @@ declare function toToolResult<T>(value: T | undefined, thrown: unknown): ToolRes
134
242
  declare const SPEC_NAME: "agenttool/v1";
135
243
  declare const SPEC_VERSION: "1.0.0-alpha";
136
244
 
137
- export { type CreateToolOptions, type CreateToolResult, SPEC_NAME, SPEC_VERSION, ToolContext, ToolDefinition, ToolError, type ToolErrorCode, type ToolErrorPayload, ToolHandle, ToolResult, ValidationResult, createTool, defineTool, toToolError, toToolResult, toolSpec, toolVerbs, validateContext, validateInput, validateOutput };
245
+ export { type CreateToolOptions, type CreateToolResult, type CursorPayload, type McpTextResult, type Page, type PageParams, type PaginateOpts, type PaginatedOptions, SPEC_NAME, SPEC_VERSION, ToolContext, ToolDefinition, ToolError, type ToolErrorCode, type ToolErrorPayload, ToolHandle, ToolResult, ToolTransformer, ValidationResult, catchErrors, createTool, decodeCursor, defineTool, encodeCursor, pageParamsShape, paginate, paginated, toToolError, toToolResult, toolSpec, toolText, toolVerbs, validateContext, validateInput, validateOutput };
package/dist/index.mjs CHANGED
@@ -1,10 +1,11 @@
1
- import { parseToolManifest, defineTool } from './chunk-VCLSUUB5.mjs';
2
- export { ToolError, defineTool, parseToolManifest, toToolError, toToolResult, toolFromManifest, toolFromManifestOnly, validateContext, validateInput, validateOutput } from './chunk-VCLSUUB5.mjs';
1
+ import { parseToolManifest, defineTool } from './chunk-7UKT5ZEH.mjs';
2
+ export { ToolError, defineTool, parseToolManifest, toToolError, toToolResult, toolFromManifest, toolFromManifestOnly, validateContext, validateInput, validateOutput } from './chunk-7UKT5ZEH.mjs';
3
3
  import { filterSerializable } from '@agentproto/define-doctype';
4
4
  import matter from 'gray-matter';
5
5
  import { mkdir, writeFile } from 'fs/promises';
6
6
  import { join, dirname } from 'path';
7
7
  import { createVerbs } from '@agentproto/manifest';
8
+ import { z } from 'zod';
8
9
 
9
10
  /**
10
11
  * @agentproto/tool v0.1.0-alpha
@@ -66,11 +67,107 @@ var toolSpec = {
66
67
  }
67
68
  };
68
69
  var toolVerbs = createVerbs(toolSpec);
70
+ function encodeCursor(payload) {
71
+ return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
72
+ }
73
+ var cursorPayloadSchema = z.object({
74
+ k: z.union([z.string(), z.number(), z.null()]),
75
+ i: z.number().int().min(0)
76
+ });
77
+ function decodeCursor(token) {
78
+ let text;
79
+ try {
80
+ text = Buffer.from(token, "base64url").toString("utf8");
81
+ } catch {
82
+ return null;
83
+ }
84
+ try {
85
+ return cursorPayloadSchema.parse(JSON.parse(text));
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ function paginate(items, params, opts) {
91
+ const limit = Math.min(Math.max(params.limit ?? 50, 1), opts.maxLimit);
92
+ let start = 0;
93
+ if (params.cursor) {
94
+ const decoded = decodeCursor(params.cursor);
95
+ if (decoded && decoded.i >= 0 && decoded.i <= items.length) start = decoded.i;
96
+ }
97
+ const end = start + limit;
98
+ const slice = items.slice(start, end);
99
+ const keyAt = (idx) => {
100
+ const item = items[idx];
101
+ return opts.keyOf && item !== void 0 ? opts.keyOf(item) : null;
102
+ };
103
+ return {
104
+ items: slice,
105
+ ...end < items.length ? { nextCursor: encodeCursor({ k: keyAt(end), i: end }) } : {},
106
+ total: items.length
107
+ };
108
+ }
109
+ function toolText(page, params) {
110
+ const fields = params?.fields;
111
+ const items = fields === void 0 ? page.items : page.items.map(
112
+ (item) => Object.fromEntries(
113
+ Object.entries(item).filter(([key]) => fields.includes(key))
114
+ )
115
+ );
116
+ return JSON.stringify({ ...page, items });
117
+ }
118
+ var pageParamsShape = {
119
+ limit: z.number().int().min(1).max(200).optional().describe("Max items per page. Default 50."),
120
+ cursor: z.string().optional().describe("Opaque token from a prior call's `nextCursor`."),
121
+ compact: z.boolean().optional().describe(
122
+ "Compact projection (fewer fields per item). Default true on tools that define a compact projection (session_list); a no-op elsewhere."
123
+ ),
124
+ full: z.boolean().optional().describe(
125
+ "Escape hatch \u2014 full, unprojected records (opts out of compact). Default false."
126
+ ),
127
+ fields: z.array(z.string()).optional().describe("Keep only these fields per item.")
128
+ };
129
+
130
+ // src/transformers.ts
131
+ function textResult(text) {
132
+ return { content: [{ type: "text", text }] };
133
+ }
134
+ function paginated(opts) {
135
+ const { project, keyOf, maxLimit = 200, itemKey = "items" } = opts;
136
+ return {
137
+ name: "paginated",
138
+ wrapShape: (shape) => ({ ...shape, ...pageParamsShape }),
139
+ wrapHandler: (handler) => async (input) => {
140
+ const params = input ?? {};
141
+ const items = await handler(input);
142
+ const full = params.full === true;
143
+ const compact = full ? false : params.compact !== false;
144
+ if (params.limit !== void 0 || params.cursor !== void 0) {
145
+ const page = paginate(items, params, { maxLimit, keyOf });
146
+ return compact ? textResult(toolText({ ...page, items: page.items.map(project) }, params)) : textResult(toolText(page, params));
147
+ }
148
+ const rows = compact ? items.map(project) : items;
149
+ return textResult(JSON.stringify({ [itemKey]: rows }));
150
+ }
151
+ };
152
+ }
153
+ function catchErrors() {
154
+ return {
155
+ name: "catchErrors",
156
+ wrapHandler: (handler) => async (input) => {
157
+ try {
158
+ return await handler(input);
159
+ } catch (err) {
160
+ const text = err instanceof Error ? err.message : String(err);
161
+ return { content: [{ type: "text", text }], isError: true };
162
+ }
163
+ }
164
+ };
165
+ }
69
166
 
70
167
  // src/index.ts
71
168
  var SPEC_NAME = "agenttool/v1";
72
169
  var SPEC_VERSION = "1.0.0-alpha";
73
170
 
74
- export { SPEC_NAME, SPEC_VERSION, createTool, toolSpec, toolVerbs };
171
+ export { SPEC_NAME, SPEC_VERSION, catchErrors, createTool, decodeCursor, encodeCursor, pageParamsShape, paginate, paginated, toolSpec, toolText, toolVerbs };
75
172
  //# sourceMappingURL=index.mjs.map
76
173
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/create-tool.ts","../src/spec.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AA0BA,SAAS,gBAAgB,GAAA,EAAuD;AAC9E,EAAA,OAAO,MAAA,CAAO,WAAA;AAAA,IACZ,OAAO,OAAA,CAAQ,GAAG,EAAE,GAAA,CAAI,CAAC,CAAC,CAAA,EAAG,CAAC,MAAM,CAAC,CAAA,CAAE,QAAQ,UAAA,EAAY,KAAK,EAAE,WAAA,EAAY,EAAG,CAAC,CAAC;AAAA,GACrF;AACF;AAwBA,eAAsB,UA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, opts)` — write a TOOL.md to disk.\n *\n * Symmetric to `parseToolManifest` (.md → handle) and `defineTool`\n * (params → handle): this takes params, validates via defineTool\n * (single source of truth — same zod schema, same cross-AIP\n * invariants), then serialises the validated frontmatter to YAML\n * and writes it under `<dir>/<id>/TOOL.md`.\n *\n * The author's body markdown is preserved verbatim in `opts.body`.\n * Pass `dryRun: true` to get the rendered string without touching\n * disk — useful for tests, the MCP server's preview, and CI lints.\n *\n * Non-frontmatter values that can't appear in YAML (zod schemas,\n * function bodies) are filtered out by `filterSerializable` from\n * `@agentproto/define-doctype`; the resulting frontmatter matches\n * what `parseToolManifest` would consume on the way back in.\n */\n\nimport { filterSerializable } from \"@agentproto/define-doctype\"\nimport matter from \"gray-matter\"\nimport { mkdir, writeFile } from \"node:fs/promises\"\nimport { dirname, join } from \"node:path\"\nimport { defineTool } from \"./define-tool.js\"\nimport type { ToolContext, ToolDefinition, ToolHandle } from \"./types.js\"\n\nfunction toSnakeCaseKeys(obj: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(obj).map(([k, v]) => [k.replace(/([A-Z])/g, \"_$1\").toLowerCase(), v]),\n )\n}\n\nexport interface CreateToolOptions {\n /** Workspace-relative or absolute directory under which to write `<id>/TOOL.md`. */\n dir: string\n /** Body markdown after the frontmatter. Defaults to a one-line stub. */\n body?: string\n /** Render only — don't write. Returns the rendered string. */\n dryRun?: boolean\n}\n\nexport interface CreateToolResult<\n TInput,\n TOutput,\n TContext extends ToolContext,\n> {\n /** The path where the file was (or would be) written. */\n path: string\n /** The validated handle returned by defineTool. */\n handle: ToolHandle<TInput, TOutput, TContext>\n /** The full rendered file contents (frontmatter + body). */\n rendered: string\n}\n\nexport async function createTool<\n TInput,\n TOutput,\n TContext extends ToolContext = ToolContext,\n>(\n params: ToolDefinition<TInput, TOutput, TContext>,\n opts: CreateToolOptions,\n): Promise<CreateToolResult<TInput, TOutput, TContext>> {\n const handle = defineTool<TInput, TOutput, TContext>(params)\n const path = join(opts.dir, handle.id, \"TOOL.md\")\n const frontmatter = filterSerializable({\n schema: \"agentproto/tool/v1\",\n ...toSnakeCaseKeys(params as unknown as Record<string, unknown>),\n }) as Record<string, unknown>\n const rendered = matter.stringify(\n opts.body ?? `# ${handle.name}\\n\\n${handle.description}\\n`,\n frontmatter,\n )\n if (!opts.dryRun) {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, rendered, \"utf8\")\n }\n return { path, handle, rendered }\n}\n","/**\n * AIP-14 doctype spec — fed to `@agentproto/manifest.createVerbs`\n * to derive create / load / list / update / resolve / delete in one\n * place. Keeping the spec separate from `define-tool.ts` lets the\n * manifest layer (and the future MCP server) iterate over a uniform\n * descriptor without each package re-implementing the wiring.\n */\n\nimport { createVerbs, type DoctypeSpec } from \"@agentproto/manifest\"\nimport { defineTool } from \"./define-tool.js\"\nimport { parseToolManifest } from \"./manifest/index.js\"\nimport type { ToolDefinition, ToolHandle } from \"./types.js\"\n\nexport const toolSpec: DoctypeSpec<\n ToolDefinition<unknown, unknown>,\n ToolHandle<unknown, unknown>\n> = {\n name: \"tool\",\n aip: 14,\n schemaLiteral: \"agentproto/tool/v1\",\n pathOf: (h) => `${h.id}/TOOL.md`,\n define: (params) =>\n defineTool(params) as ToolHandle<unknown, unknown>,\n parse: (source) => {\n const m = parseToolManifest(source)\n const fm = m.frontmatter\n // `createVerbs.load` feeds this frontmatter straight to `define`\n // (= `defineTool`), which reads camelCase keys. The manifest uses\n // snake_case for multi-word fields, so they must be renamed here or\n // `defineTool` silently falls back to its defaults. Single-word fields\n // (mutates, approval, idempotent, tags, metadata, requires) share the\n // same key in both conventions and pass through unchanged.\n const frontmatter: Record<string, unknown> = {\n id: fm.id,\n name: fm.name,\n description: fm.description,\n version: fm.version,\n ...(fm.mutates !== undefined && { mutates: fm.mutates }),\n ...(fm.requires !== undefined && { requires: fm.requires }),\n ...(fm.approval !== undefined && { approval: fm.approval }),\n ...(fm.risk_level !== undefined && { riskLevel: fm.risk_level }),\n ...(fm.cost_class !== undefined && { costClass: fm.cost_class }),\n ...(fm.timeout_ms !== undefined && { timeoutMs: fm.timeout_ms }),\n ...(fm.idempotent !== undefined && { idempotent: fm.idempotent }),\n ...(fm.tags !== undefined && { tags: fm.tags }),\n ...(fm.metadata !== undefined && { metadata: fm.metadata }),\n // AIP-16 IO blocks pass through under the same keys.\n ...(fm.inputs !== undefined && { inputs: fm.inputs }),\n ...(fm.outputs !== undefined && { outputs: fm.outputs }),\n }\n return { frontmatter, body: m.body }\n },\n}\n\nexport const toolVerbs = createVerbs(toolSpec)\n","/**\n * @agentproto/tool — AIP-14 TOOL.md `defineTool` reference impl.\n *\n * Vendor-neutral tool **contract** registration: an author writes\n * `defineTool({...})` and the runtime returns a `ToolHandle` carrying\n * identity, schemas, side-effect profile, approval class, and\n * provider routing hints. Bodies live on AIP-30 PROVIDER manifests;\n * invocation goes through `@agentproto/driver`.\n *\n * Spec: https://agentproto.sh/docs/aip-14\n */\n\nexport const SPEC_NAME = \"agenttool/v1\" as const\nexport const SPEC_VERSION = \"1.0.0-alpha\" as const\n\nexport {\n defineTool,\n validateInput,\n validateContext,\n validateOutput,\n} from \"./define-tool.js\"\n// Standalone create-tool kept for back-compat; new code should import\n// the unified verb surface (`toolVerbs.create`, `.load`, `.list`,\n// `.update`, `.resolve`, `.delete`) from `./spec.js`.\nexport {\n createTool,\n type CreateToolOptions,\n type CreateToolResult,\n} from \"./create-tool.js\"\nexport { toolSpec, toolVerbs } from \"./spec.js\"\nexport {\n parseToolManifest,\n toolFromManifest,\n toolFromManifestOnly,\n type ToolManifest,\n type ToolManifestFrontmatter,\n} from \"./manifest/index.js\"\nexport {\n ToolError,\n toToolError,\n toToolResult,\n type ToolErrorCode,\n type ToolErrorPayload,\n} from \"./errors.js\"\nexport type {\n ToolDefinition,\n ToolHandle,\n ToolContext,\n ToolCapabilities,\n ApprovalClass,\n DriverConstraints,\n DriverKind,\n RetryPolicy,\n ToolResult,\n ValidationResult,\n ValidationFailure,\n ValidationSuccess,\n} from \"./types.js\"\n"]}
1
+ {"version":3,"sources":["../src/create-tool.ts","../src/spec.ts","../src/envelope.ts","../src/transformers.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;AA0BA,SAAS,gBAAgB,GAAA,EAAuD;AAC9E,EAAA,OAAO,MAAA,CAAO,WAAA;AAAA,IACZ,OAAO,OAAA,CAAQ,GAAG,EAAE,GAAA,CAAI,CAAC,CAAC,CAAA,EAAG,CAAC,MAAM,CAAC,CAAA,CAAE,QAAQ,UAAA,EAAY,KAAK,EAAE,WAAA,EAAY,EAAG,CAAC,CAAC;AAAA,GACrF;AACF;AAwBA,eAAsB,UAAA,CAKpB,QACA,IAAA,EACsD;AACtD,EAAA,MAAM,MAAA,GAAS,WAAsC,MAAM,CAAA;AAC3D,EAAA,MAAM,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAA,CAAO,IAAI,SAAS,CAAA;AAChD,EAAA,MAAM,cAAc,kBAAA,CAAmB;AAAA,IACrC,MAAA,EAAQ,oBAAA;AAAA,IACR,GAAG,gBAAgB,MAA4C;AAAA,GAChE,CAAA;AACD,EAAA,MAAM,WAAW,MAAA,CAAO,SAAA;AAAA,IACtB,IAAA,CAAK,IAAA,IAAQ,CAAA,EAAA,EAAK,MAAA,CAAO,IAAI;;AAAA,EAAO,OAAO,WAAW;AAAA,CAAA;AAAA,IACtD;AAAA,GACF;AACA,EAAA,IAAI,CAAC,KAAK,MAAA,EAAQ;AAChB,IAAA,MAAM,MAAM,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC9C,IAAA,MAAM,SAAA,CAAU,IAAA,EAAM,QAAA,EAAU,MAAM,CAAA;AAAA,EACxC;AACA,EAAA,OAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,QAAA,EAAS;AAClC;AChEO,IAAM,QAAA,GAGT;AAAA,EACF,IAAA,EAAM,MAAA;AAAA,EACN,GAAA,EAAK,EAAA;AAAA,EACL,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AAC5D,QAAA,OAAO,EAAE,OAAA,EAAS,CAAC,EAAE,IAAA,EAAM,QAAQ,IAAA,EAAM,CAAA,EAAG,OAAA,EAAS,IAAA,EAAK;AAAA,MAC5D;AAAA,IACF;AAAA,GACF;AACF;;;AC1FO,IAAM,SAAA,GAAY;AAClB,IAAM,YAAA,GAAe","file":"index.mjs","sourcesContent":["/**\n * `createTool(params, opts)` — write a TOOL.md to disk.\n *\n * Symmetric to `parseToolManifest` (.md → handle) and `defineTool`\n * (params → handle): this takes params, validates via defineTool\n * (single source of truth — same zod schema, same cross-AIP\n * invariants), then serialises the validated frontmatter to YAML\n * and writes it under `<dir>/<id>/TOOL.md`.\n *\n * The author's body markdown is preserved verbatim in `opts.body`.\n * Pass `dryRun: true` to get the rendered string without touching\n * disk — useful for tests, the MCP server's preview, and CI lints.\n *\n * Non-frontmatter values that can't appear in YAML (zod schemas,\n * function bodies) are filtered out by `filterSerializable` from\n * `@agentproto/define-doctype`; the resulting frontmatter matches\n * what `parseToolManifest` would consume on the way back in.\n */\n\nimport { filterSerializable } from \"@agentproto/define-doctype\"\nimport matter from \"gray-matter\"\nimport { mkdir, writeFile } from \"node:fs/promises\"\nimport { dirname, join } from \"node:path\"\nimport { defineTool } from \"./define-tool.js\"\nimport type { ToolContext, ToolDefinition, ToolHandle } from \"./types.js\"\n\nfunction toSnakeCaseKeys(obj: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(obj).map(([k, v]) => [k.replace(/([A-Z])/g, \"_$1\").toLowerCase(), v]),\n )\n}\n\nexport interface CreateToolOptions {\n /** Workspace-relative or absolute directory under which to write `<id>/TOOL.md`. */\n dir: string\n /** Body markdown after the frontmatter. Defaults to a one-line stub. */\n body?: string\n /** Render only — don't write. Returns the rendered string. */\n dryRun?: boolean\n}\n\nexport interface CreateToolResult<\n TInput,\n TOutput,\n TContext extends ToolContext,\n> {\n /** The path where the file was (or would be) written. */\n path: string\n /** The validated handle returned by defineTool. */\n handle: ToolHandle<TInput, TOutput, TContext>\n /** The full rendered file contents (frontmatter + body). */\n rendered: string\n}\n\nexport async function createTool<\n TInput,\n TOutput,\n TContext extends ToolContext = ToolContext,\n>(\n params: ToolDefinition<TInput, TOutput, TContext>,\n opts: CreateToolOptions,\n): Promise<CreateToolResult<TInput, TOutput, TContext>> {\n const handle = defineTool<TInput, TOutput, TContext>(params)\n const path = join(opts.dir, handle.id, \"TOOL.md\")\n const frontmatter = filterSerializable({\n schema: \"agentproto/tool/v1\",\n ...toSnakeCaseKeys(params as unknown as Record<string, unknown>),\n }) as Record<string, unknown>\n const rendered = matter.stringify(\n opts.body ?? `# ${handle.name}\\n\\n${handle.description}\\n`,\n frontmatter,\n )\n if (!opts.dryRun) {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, rendered, \"utf8\")\n }\n return { path, handle, rendered }\n}\n","/**\n * AIP-14 doctype spec — fed to `@agentproto/manifest.createVerbs`\n * to derive create / load / list / update / resolve / delete in one\n * place. Keeping the spec separate from `define-tool.ts` lets the\n * manifest layer (and the future MCP server) iterate over a uniform\n * descriptor without each package re-implementing the wiring.\n */\n\nimport { createVerbs, type DoctypeSpec } from \"@agentproto/manifest\"\nimport { defineTool } from \"./define-tool.js\"\nimport { parseToolManifest } from \"./manifest/index.js\"\nimport type { ToolDefinition, ToolHandle } from \"./types.js\"\n\nexport const toolSpec: DoctypeSpec<\n ToolDefinition<unknown, unknown>,\n ToolHandle<unknown, unknown>\n> = {\n name: \"tool\",\n aip: 14,\n schemaLiteral: \"agentproto/tool/v1\",\n pathOf: (h) => `${h.id}/TOOL.md`,\n define: (params) =>\n defineTool(params) as ToolHandle<unknown, unknown>,\n parse: (source) => {\n const m = parseToolManifest(source)\n const fm = m.frontmatter\n // `createVerbs.load` feeds this frontmatter straight to `define`\n // (= `defineTool`), which reads camelCase keys. The manifest uses\n // snake_case for multi-word fields, so they must be renamed here or\n // `defineTool` silently falls back to its defaults. Single-word fields\n // (mutates, approval, idempotent, tags, metadata, requires) share the\n // same key in both conventions and pass through unchanged.\n const frontmatter: Record<string, unknown> = {\n id: fm.id,\n name: fm.name,\n description: fm.description,\n version: fm.version,\n ...(fm.mutates !== undefined && { mutates: fm.mutates }),\n ...(fm.requires !== undefined && { requires: fm.requires }),\n ...(fm.approval !== undefined && { approval: fm.approval }),\n ...(fm.risk_level !== undefined && { riskLevel: fm.risk_level }),\n ...(fm.cost_class !== undefined && { costClass: fm.cost_class }),\n ...(fm.timeout_ms !== undefined && { timeoutMs: fm.timeout_ms }),\n ...(fm.idempotent !== undefined && { idempotent: fm.idempotent }),\n ...(fm.tags !== undefined && { tags: fm.tags }),\n ...(fm.metadata !== undefined && { metadata: fm.metadata }),\n // AIP-16 IO blocks pass through under the same keys.\n ...(fm.inputs !== undefined && { inputs: fm.inputs }),\n ...(fm.outputs !== undefined && { outputs: fm.outputs }),\n }\n return { frontmatter, body: m.body }\n },\n}\n\nexport const toolVerbs = createVerbs(toolSpec)\n","import { z } from \"zod\"\n\n/**\n * Shared pagination primitives (moved here from `@agentproto/runtime`'s\n * `tool-envelope.ts` so the `paginated()` ToolTransformer can reuse the\n * exact cursor/limit semantics the daemon's list tools already depend on).\n * `@agentproto/runtime` re-exports this module verbatim, so existing\n * imports are unchanged.\n */\n\n/** Shared pagination params, spread into every list tool's input schema. */\nexport interface PageParams {\n limit?: number\n cursor?: string\n since?: number\n compact?: boolean\n full?: boolean\n fields?: string[]\n}\n\nexport interface Page<T> {\n items: T[]\n nextCursor?: string\n total?: number\n truncated?: boolean\n}\n\n/** Opaque cursor: base64(JSON `{ k: keysetValue, i: index }`). */\nexport interface CursorPayload {\n k: string | number | null\n i: number\n}\n\nexport function encodeCursor(payload: CursorPayload): string {\n return Buffer.from(JSON.stringify(payload), \"utf8\").toString(\"base64url\")\n}\n\nconst cursorPayloadSchema = z.object({\n k: z.union([z.string(), z.number(), z.null()]),\n i: z.number().int().min(0),\n})\n\n/** No `unknown`/`as`: the JSON boundary is typed by zod's safeParse/parse. */\nexport function decodeCursor(token: string): CursorPayload | null {\n let text: string\n try {\n text = Buffer.from(token, \"base64url\").toString(\"utf8\")\n } catch {\n return null\n }\n try {\n return cursorPayloadSchema.parse(JSON.parse(text))\n } catch {\n return null\n }\n}\n\nexport interface PaginateOpts<T> {\n maxLimit: number\n keyOf?: (item: T) => string | number | null\n}\n\nexport function paginate<T>(items: readonly T[], params: PageParams, opts: PaginateOpts<T>): Page<T> {\n const limit = Math.min(Math.max(params.limit ?? 50, 1), opts.maxLimit)\n let start = 0\n if (params.cursor) {\n const decoded = decodeCursor(params.cursor)\n if (decoded && decoded.i >= 0 && decoded.i <= items.length) start = decoded.i\n }\n const end = start + limit\n const slice = items.slice(start, end)\n const keyAt = (idx: number): string | number | null => {\n const item = items[idx]\n return opts.keyOf && item !== undefined ? opts.keyOf(item) : null\n }\n return {\n items: slice,\n ...(end < items.length ? { nextCursor: encodeCursor({ k: keyAt(end), i: end }) } : {}),\n total: items.length,\n }\n}\n\n/**\n * Compact serializer — replaces every `JSON.stringify(x, null, 2)` in list handlers.\n *\n * When `params.fields` is supplied, an explicit allowlist is applied to every\n * item (mechanically, across all call sites): items keep only the named keys.\n * Absent `fields`, the output is byte-identical to `JSON.stringify(page)`.\n */\nexport function toolText<T extends object>(page: Page<T>, params?: Pick<PageParams, \"fields\">): string {\n const fields = params?.fields\n const items =\n fields === undefined\n ? page.items\n : page.items.map(item =>\n Object.fromEntries(\n Object.entries(item).filter(([key]) => fields.includes(key)),\n ),\n )\n return JSON.stringify({ ...page, items })\n}\n\n/** Zod fragment to spread into each list tool's input schema. */\nexport const pageParamsShape = {\n limit: z.number().int().min(1).max(200).optional().describe(\"Max items per page. Default 50.\"),\n cursor: z.string().optional().describe(\"Opaque token from a prior call's `nextCursor`.\"),\n compact: z\n .boolean()\n .optional()\n .describe(\n \"Compact projection (fewer fields per item). Default true on tools \" +\n \"that define a compact projection (session_list); a no-op elsewhere.\",\n ),\n full: z\n .boolean()\n .optional()\n .describe(\n \"Escape hatch — full, unprojected records (opts out of compact). \" +\n \"Default false.\",\n ),\n fields: z.array(z.string()).optional().describe(\"Keep only these fields per item.\"),\n} as const\n","import type { ZodRawShape } from \"zod\"\nimport {\n paginate,\n pageParamsShape,\n toolText,\n type PageParams,\n} from \"./envelope.js\"\nimport type { ToolTransformer } from \"./types.js\"\n\n/**\n * Concrete {@link ToolTransformer}s — cross-cutting concerns composed by\n * MCP-facing adapters (`toMcpTool`) around a tool's handler pipeline.\n */\n\n/** The MCP text-result shape transformers terminate the pipeline into. */\nexport interface McpTextResult {\n content: Array<{ type: \"text\"; text: string }>\n isError?: boolean\n}\n\nfunction textResult(text: string): McpTextResult {\n return { content: [{ type: \"text\", text }] }\n}\n\nexport interface PaginatedOptions<TItem> {\n /**\n * REQUIRED per-item compact projection. Requiring it is the point: there\n * is no code path that accepts the `compact` param without an actual\n * compact projection behind it, killing the \"declared but dead param\"\n * bug class. Pass the identity function only if you truly want\n * `compact` to be a no-op.\n */\n project: (item: TItem) => object\n /** Key function for the opaque pagination cursor. */\n keyOf?: (item: TItem) => string | number | null\n /** Hard ceiling on `limit` (default 200 — matches the daemon tools). */\n maxLimit?: number\n /**\n * Wrapper key for the NON-paginated output. With no `limit`/`cursor`,\n * legacy list tools returned `{ sessions: [...] }` rather than the page\n * envelope; set this to reproduce that wrapper (default `\"items\"`).\n */\n itemKey?: string\n}\n\n/**\n * Pagination transformer — adds {@link pageParamsShape} to the input shape\n * and wraps the handler (which must return the FULL, unprojected item\n * array) with the shared cursor/limit semantics:\n *\n * - `limit`/`cursor` present → the `{ items, nextCursor?, total }` page\n * envelope via `paginate` + `toolText` (cursor/limit semantics are the\n * exact ones the daemon's list tools already depend on).\n * - neither present → the legacy `{ [itemKey]: [...] }` wrapper, no\n * envelope fields.\n *\n * Rows are COMPACT by default (`project`); `full: true` / `compact: false`\n * returns the unprojected records. `fields` is a per-item allowlist\n * applied on the paginated envelope branch (matching existing behavior).\n */\nexport function paginated<TItem extends object>(\n opts: PaginatedOptions<TItem>,\n): ToolTransformer<unknown, readonly TItem[], McpTextResult> {\n const { project, keyOf, maxLimit = 200, itemKey = \"items\" } = opts\n return {\n name: \"paginated\",\n wrapShape: (shape: ZodRawShape): ZodRawShape => ({ ...shape, ...pageParamsShape }),\n wrapHandler: handler => async input => {\n const params = (input ?? {}) as PageParams\n const items = (await handler(input)) as readonly TItem[]\n const full = params.full === true\n const compact = full ? false : params.compact !== false\n if (params.limit !== undefined || params.cursor !== undefined) {\n const page = paginate(items, params, { maxLimit, keyOf })\n return compact\n ? textResult(toolText({ ...page, items: page.items.map(project) }, params))\n : textResult(toolText(page, params))\n }\n const rows = compact ? items.map(project) : items\n return textResult(JSON.stringify({ [itemKey]: rows }))\n },\n }\n}\n\n/**\n * Error-normalization transformer — wraps the handler so ANY thrown error\n * becomes the single canonical MCP error result\n * `{ content: [{ type: \"text\", text: <message> }], isError: true }`,\n * replacing the ~150 copy-pasted inline catch blocks.\n */\nexport function catchErrors(): ToolTransformer<unknown, unknown, McpTextResult> {\n return {\n name: \"catchErrors\",\n wrapHandler: handler => async input => {\n try {\n return (await handler(input)) as McpTextResult\n } catch (err) {\n const text = err instanceof Error ? err.message : String(err)\n return { content: [{ type: \"text\", text }], isError: true }\n }\n },\n }\n}\n","/**\n * @agentproto/tool — AIP-14 TOOL.md `defineTool` reference impl.\n *\n * Vendor-neutral tool **contract** registration: an author writes\n * `defineTool({...})` and the runtime returns a `ToolHandle` carrying\n * identity, schemas, side-effect profile, approval class, and\n * provider routing hints. Bodies live on AIP-30 PROVIDER manifests;\n * invocation goes through `@agentproto/driver`.\n *\n * Spec: https://agentproto.sh/docs/aip-14\n */\n\nexport const SPEC_NAME = \"agenttool/v1\" as const\nexport const SPEC_VERSION = \"1.0.0-alpha\" as const\n\nexport {\n defineTool,\n validateInput,\n validateContext,\n validateOutput,\n} from \"./define-tool.js\"\n// Standalone create-tool kept for back-compat; new code should import\n// the unified verb surface (`toolVerbs.create`, `.load`, `.list`,\n// `.update`, `.resolve`, `.delete`) from `./spec.js`.\nexport {\n createTool,\n type CreateToolOptions,\n type CreateToolResult,\n} from \"./create-tool.js\"\nexport { toolSpec, toolVerbs } from \"./spec.js\"\nexport {\n parseToolManifest,\n toolFromManifest,\n toolFromManifestOnly,\n type ToolManifest,\n type ToolManifestFrontmatter,\n} from \"./manifest/index.js\"\nexport {\n ToolError,\n toToolError,\n toToolResult,\n type ToolErrorCode,\n type ToolErrorPayload,\n} from \"./errors.js\"\nexport {\n paginated,\n catchErrors,\n type McpTextResult,\n type PaginatedOptions,\n} from \"./transformers.js\"\nexport {\n paginate,\n toolText,\n encodeCursor,\n decodeCursor,\n pageParamsShape,\n type Page,\n type PageParams,\n type PaginateOpts,\n type CursorPayload,\n} from \"./envelope.js\"\nexport type {\n ToolDefinition,\n ToolHandle,\n ToolTransformer,\n ToolContext,\n ToolCapabilities,\n ApprovalClass,\n DriverConstraints,\n DriverKind,\n RetryPolicy,\n ToolResult,\n ValidationResult,\n ValidationFailure,\n ValidationSuccess,\n} from \"./types.js\"\n"]}
@@ -1,2 +1,2 @@
1
1
  import 'zod';
2
- export { f as ToolManifest, g as ToolManifestFrontmatter, p as parseToolManifest, t as toolFromManifest, j as toolFromManifestOnly, k as toolManifestFrontmatterSchema } from '../index-63aR8ryG.js';
2
+ export { g as ToolManifest, h as ToolManifestFrontmatter, p as parseToolManifest, t as toolFromManifest, k as toolFromManifestOnly, l as toolManifestFrontmatterSchema } from '../index-DpcQ_sMe.js';
@@ -1,3 +1,3 @@
1
- export { parseToolManifest, toolFromManifest, toolFromManifestOnly, toolManifestFrontmatterSchema } from '../chunk-VCLSUUB5.mjs';
1
+ export { parseToolManifest, toolFromManifest, toolFromManifestOnly, toolManifestFrontmatterSchema } from '../chunk-7UKT5ZEH.mjs';
2
2
  //# sourceMappingURL=index.mjs.map
3
3
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/tool",
3
- "version": "0.2.2",
3
+ "version": "0.3.1",
4
4
  "description": "agentproto/tool-runtime — reference implementation of AIP-14 TOOL.md `defineTool` contract. Vendor-neutral tool registration with validated input/output schemas, structured error envelopes, and side-effect declarations. Per-framework adapters (Mastra, LangChain, A2A) consume the produced ToolHandle.",
5
5
  "keywords": [
6
6
  "agentproto",
@@ -48,16 +48,16 @@
48
48
  "dependencies": {
49
49
  "ajv": "^8.20.0",
50
50
  "gray-matter": "^4.0.3",
51
- "zod": "^4.5.4",
52
- "@agentproto/manifest": "0.2.1",
53
- "@agentproto/define-doctype": "0.1.1"
51
+ "zod": "^4.6.5",
52
+ "@agentproto/define-doctype": "0.1.2",
53
+ "@agentproto/manifest": "0.2.2"
54
54
  },
55
55
  "devDependencies": {
56
- "@types/node": "^25.6.2",
56
+ "@types/node": "^25.9.5",
57
57
  "tsup": "^8.5.1",
58
58
  "typescript": "^5.9.3",
59
- "vitest": "^3.2.4",
60
- "@agentproto/tooling": "0.1.0-alpha.0"
59
+ "vitest": "^3.2.7",
60
+ "@agentproto/tooling": "0.1.0"
61
61
  },
62
62
  "scripts": {
63
63
  "dev": "tsup --watch",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/define-tool.ts","../src/manifest/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AA6BO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EACA,SAAA;AAAA,EACA,KAAA;AAAA,EAET,YAAY,OAAA,EAA2B;AACrC,IAAA,KAAA,CAAM,QAAQ,OAAO,CAAA;AACrB,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,KAAA;AACtC,IAAA,IAAA,CAAK,QAAQ,OAAA,CAAQ,KAAA;AAAA,EACvB;AAAA,EAEA,MAAA,GAA2B;AACzB,IAAA,OAAO;AAAA,MACL,M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AA,CAAG,QAAA;AAAA,IACb,WAAW,EAAA,CAAG,UAAA;AAAA,IACd,WAAW,EAAA,CAAG,UAAA;AAAA,IACd,WAAW,EAAA,CAAG,UAAA;AAAA,IACd,YAAY,EAAA,CAAG,UAAA;AAAA,IACf,MAAM,EAAA,CAAG,IAAA;AAAA,IACT,UAAU,EAAA,CAAG;AAAA,GACd,CAAA;AACH;AAuBO,SAAS,iBAId,IAAA,EAKwC;AACxC,EAAA,MAAM,EAAA,GAAK,KAAK,QAAA,CAAS,WAAA;AACzB,EAAA,OAAO,UAAA,CAAsC;AAAA,IAC3C,IAAI,EAAA,CAAG,EAAA;AAAA,IACP,MAAM,EAAA,CAAG,IAAA;AAAA,IACT,aAAa,EAAA,CAAG,WAAA;AAAA,IAChB,SAAS,EAAA,CAAG,OAAA;AAAA,IACZ,aAAa,IAAA,CAAK,WAAA;AAAA,IAClB,cAAc,IAAA,CAAK,YAAA;AAAA,IACnB,QAAQ,EAAA,CAAG,MAAA;AAAA,IACX,SAAS,EAAA,CAAG,OAAA;AAAA,IACZ,eAAe,IAAA,CAAK,aAAA;AAAA,IACpB,SAAS,EAAA,CAAG,OAAA;AAAA,IACZ,UAAU,EAAA,CAAG,QAAA;AAAA,IACb,UAAU,EAAA,CAAG,QAAA;AAAA,IACb,WAAW,EAAA,CAAG,UAAA;AAAA,IACd,WAAW,EAAA,CAAG,UAAA;AAAA,IACd,WAAW,EAAA,CAAG,UAAA;AAAA,IACd,YAAY,EAAA,CAAG,UAAA;AAAA,IACf,MAAM,EAAA,CAAG,IAAA;AAAA,IACT,UAAU,EAAA,CAAG;AAAA,GACd,CAAA;AACH","file":"chunk-VCLSUUB5.mjs","sourcesContent":["import type { ToolResult } from \"./types.js\"\n\n/**\n * AIP-14 conventional error codes. Tool-specific codes MAY use a domain\n * prefix (`\"stripe:card_declined\"`).\n */\nexport type ToolErrorCode =\n | \"input_invalid\"\n | \"output_invalid\"\n | \"unauthorised\"\n | \"not_found\"\n | \"rate_limited\"\n | \"timeout\"\n | \"upstream_error\"\n | \"internal\"\n | (string & {})\n\nexport interface ToolErrorPayload {\n code: ToolErrorCode\n message: string\n retryable?: boolean\n cause?: unknown\n}\n\n/**\n * Structured error thrown by tool bodies. Adapters wrap this into the\n * standard {@link ToolResult} envelope; bodies MUST throw it (never\n * return error objects).\n */\nexport class ToolError extends Error {\n readonly code: ToolErrorCode\n readonly retryable: boolean\n readonly cause: unknown\n\n constructor(payload: ToolErrorPayload) {\n super(payload.message)\n this.name = \"ToolError\"\n this.code = payload.code\n this.retryable = payload.retryable ?? false\n this.cause = payload.cause\n }\n\n toJSON(): ToolErrorPayload {\n return {\n code: this.code,\n message: this.message,\n retryable: this.retryable,\n ...(this.cause !== undefined ? { cause: this.cause } : {}),\n }\n }\n}\n\n/**\n * Wrap an unknown thrown value into a {@link ToolError}. Used by adapters\n * to normalise non-ToolError throws into the standard envelope.\n */\nexport function toToolError(thrown: unknown): ToolError {\n if (thrown instanceof ToolError) return thrown\n if (thrown instanceof Error) {\n return new ToolError({\n code: \"internal\",\n message: thrown.message,\n cause: thrown,\n })\n }\n return new ToolError({\n code: \"internal\",\n message: String(thrown),\n cause: thrown,\n })\n}\n\n/**\n * Adapter helper: project a thrown ToolError (or any throw) into the\n * standard {@link ToolResult} envelope. Adapters MUST do this; bodies MUST NOT.\n */\nexport function toToolResult<T>(\n value: T | undefined,\n thrown: unknown\n): ToolResult<T> {\n if (thrown !== undefined) {\n const err = toToolError(thrown)\n return { ok: false, error: err.toJSON() }\n }\n return { ok: true, value: value as T }\n}\n","import { createDoctype } from \"@agentproto/define-doctype\"\nimport Ajv from \"ajv\"\nimport type { ZodType } from \"zod\"\nimport { ToolError } from \"./errors.js\"\nimport type {\n ApprovalClass,\n DriverConstraints,\n DriverKind,\n ToolCapabilities,\n ToolContext,\n ToolDefinition,\n ToolHandle,\n ValidationResult,\n} from \"./types.js\"\n\nconst PROVIDER_KINDS: readonly DriverKind[] = [\n \"cli\",\n \"http\",\n \"mcp\",\n \"sdk\",\n \"builtin\",\n]\n\n/**\n * AIP-14 reference implementation of `defineTool`.\n *\n * Returns a {@link ToolHandle} with defaults applied. The handle is a\n * pure contract — schemas, governance metadata, provider routing\n * hints. Bodies live on AIP-30 PROVIDER manifests; invocation goes\n * through provider-runtime's resolver.\n *\n * Built on `createDoctype` from `@agentproto/define-doctype`: the\n * id-pattern + description-length validation and the top-level\n * `Object.freeze` are shared with every other AIP defineX. The\n * spec-14-specific parts (migration guard for `execute`, defaulting\n * `approval` from `mutates`, freezing nested arrays/objects) live in\n * `validate` and `build` below.\n *\n * Conformance highlights ([§ Conformance rules](https://agentproto.sh/docs/aip-14)):\n * - No `execute` field on the contract — bodies are providers' job.\n * - `defineTool` MUST refuse a definition carrying `execute` (migration error).\n * - No I/O at module load — `defineTool(...)` is pure construction.\n */\nconst constructTool = createDoctype<\n ToolDefinition<unknown, unknown, ToolContext>,\n ToolHandle<unknown, unknown, ToolContext>\n>({\n aip: 14,\n name: \"tool\",\n validate(def) {\n // Migration guard: catch authors trying to ship a body on the contract.\n // The body lives on a PROVIDER (per AIP-30); reject at construction.\n if (\"execute\" in (def as unknown as Record<string, unknown>)) {\n throw new Error(\n `defineTool: id='${def.id}' carries an 'execute' property. ` +\n `Bodies live on AIP-30 PROVIDER manifests, not on the TOOL contract. ` +\n `See https://agentproto.sh/docs/aip-30 for migration.`,\n )\n }\n },\n build(def) {\n return {\n id: def.id,\n name: def.name ?? def.id,\n description: def.description,\n version: def.version,\n inputSchema: def.inputSchema,\n outputSchema: def.outputSchema,\n inputs: def.inputs ? Object.freeze({ ...def.inputs }) : undefined,\n outputs: def.outputs ? Object.freeze({ ...def.outputs }) : undefined,\n contextSchema: def.contextSchema,\n mutates: Object.freeze([...(def.mutates ?? [])]),\n requires: freezeCapabilities(def.requires),\n approval: defaultApproval(def.approval, def.mutates),\n riskLevel: def.riskLevel ?? 0,\n costClass: def.costClass ?? \"trivial\",\n timeoutMs: def.timeoutMs ?? 30_000,\n retry: def.retry,\n tags: Object.freeze([...(def.tags ?? [])]),\n metadata: Object.freeze({ ...(def.metadata ?? {}) }),\n idempotent: def.idempotent ?? false,\n defaultImplementation: def.defaultImplementation,\n driverConstraints: freezeProviderConstraints(def.driverConstraints),\n }\n },\n})\n\n/**\n * Public-facing `defineTool` — typed wrapper around `constructTool`\n * that preserves the per-call `<TInput, TOutput, TContext>` inference\n * so callers don't write any generics. The wrapper exists purely for\n * generic propagation; the runtime body is the meta-factory above.\n */\nexport function defineTool<\n TInput,\n TOutput,\n TContext extends ToolContext = ToolContext,\n>(\n definition: ToolDefinition<TInput, TOutput, TContext>,\n): ToolHandle<TInput, TOutput, TContext> {\n return constructTool(\n definition as ToolDefinition<unknown, unknown, ToolContext>,\n ) as unknown as ToolHandle<TInput, TOutput, TContext>\n}\n\n/**\n * Validate input against a tool's `inputSchema`. Returns a typed\n * {@link ValidationResult}; provider runtimes MUST call this BEFORE\n * dispatching to the provider's body.\n *\n * Priority:\n * 1. zod `inputSchema` (v0.1) — used when present.\n * 2. JSON Schema `inputs` (v0.2) — fallback for manifest-only tools.\n * 3. No schema — passthrough (returns `ok: true`).\n */\nexport function validateInput<TInput>(\n handle: Pick<ToolHandle<TInput>, \"id\" | \"inputSchema\" | \"inputs\">,\n input: unknown,\n): ValidationResult<TInput> {\n if (handle.inputSchema) {\n const result = handle.inputSchema.safeParse(input)\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"input_invalid\",\n message: `id='${handle.id}': ${formatZodIssues(result.error.issues)}`,\n cause: result.error.issues,\n },\n }\n }\n return { ok: true, value: result.data as TInput }\n }\n if (handle.inputs) {\n return validateJsonSchema<TInput>(handle.id, handle.inputs, input)\n }\n return { ok: true, value: input as TInput }\n}\n\n/**\n * Validate context against a tool's `contextSchema` (when declared).\n * Returns a typed {@link ValidationResult}; provider runtimes MUST\n * call this BEFORE dispatching when the contract has a contextSchema.\n *\n * Tools without a contextSchema accept any context shape; this helper\n * returns the input verbatim in that case.\n *\n * Context validation uses only zod (no JSON Schema fallback) — context\n * schemas are always authored in TS, never in manifests.\n */\nexport function validateContext<TContext extends ToolContext = ToolContext>(\n handle: Pick<ToolHandle<unknown, unknown, TContext>, \"id\" | \"contextSchema\">,\n context: unknown,\n): ValidationResult<TContext> {\n if (!handle.contextSchema) {\n return { ok: true, value: context as TContext }\n }\n const result = handle.contextSchema.safeParse(context)\n if (!result.success) {\n return {\n ok: false,\n error: {\n code: \"input_invalid\",\n message: `id='${handle.id}': context does not match contextSchema — ${formatZodIssues(result.error.issues)}`,\n field: \"context\",\n cause: result.error.issues,\n },\n }\n }\n return { ok: true, value: result.data as TContext }\n}\n\n/**\n * Validate output against a tool's `outputSchema`. Returns the typed\n * value on success; throws {@link ToolError} with code `\"output_invalid\"`\n * on contract violation.\n *\n * Priority:\n * 1. zod `outputSchema` (v0.1) — used when present.\n * 2. JSON Schema `outputs` (v0.2) — fallback for manifest-only tools.\n * 3. No schema — passthrough (returns the value as-is).\n */\nexport function validateOutput<TOutput>(\n handle: Pick<ToolHandle<unknown, TOutput>, \"id\" | \"outputSchema\" | \"outputs\">,\n output: unknown,\n): TOutput {\n if (handle.outputSchema) {\n const result = handle.outputSchema.safeParse(output)\n if (!result.success) {\n throw new ToolError({\n code: \"output_invalid\",\n message: `id='${handle.id}': provider produced output that does not match outputSchema — ${formatZodIssues(result.error.issues)}`,\n cause: result.error.issues,\n })\n }\n return result.data as TOutput\n }\n if (handle.outputs) {\n const result = validateJsonSchema<TOutput>(handle.id, handle.outputs, output)\n if (!result.ok) {\n throw new ToolError({\n code: \"output_invalid\",\n message: result.error.message,\n cause: result.error.cause,\n })\n }\n return result.value\n }\n return output as TOutput\n}\n\nfunction defaultApproval(\n declared: ApprovalClass | undefined,\n mutates: readonly string[] | undefined,\n): ApprovalClass {\n if (declared) return declared\n return mutates && mutates.length > 0 ? \"on-mutate\" : \"auto\"\n}\n\nfunction freezeCapabilities(\n caps: ToolCapabilities | undefined,\n): Readonly<ToolCapabilities> {\n return Object.freeze({\n network: Object.freeze([...(caps?.network ?? [])]),\n secrets: Object.freeze([...(caps?.secrets ?? [])]),\n tools: Object.freeze([...(caps?.tools ?? [])]),\n })\n}\n\nfunction freezeProviderConstraints(\n c: DriverConstraints | undefined,\n): Required<DriverConstraints> {\n const forbid = (c?.forbid ?? []).filter((k): k is DriverKind =>\n PROVIDER_KINDS.includes(k as DriverKind),\n )\n const requireKind = (c?.requireKind ?? []).filter((k): k is DriverKind =>\n PROVIDER_KINDS.includes(k as DriverKind),\n )\n return Object.freeze({\n forbid: Object.freeze(forbid) as readonly DriverKind[],\n requireKind: Object.freeze(requireKind) as readonly DriverKind[],\n })\n}\n\nfunction formatZodIssues(\n issues: ReadonlyArray<{ path: ReadonlyArray<PropertyKey>; message: string }>,\n): string {\n return issues\n .map((i) => `${i.path.length > 0 ? i.path.join(\".\") + \": \" : \"\"}${i.message}`)\n .join(\"; \")\n}\n\n// Shared Ajv instance — created once at module load.\n// allErrors: true so we surface all violations, not just the first.\nconst _ajv = new Ajv({ allErrors: true })\n\n// Validator cache keyed by schema object identity. Avoids repeated _ajv.compile()\n// calls (which go through Ajv's internal registry) and lets GC collect validators\n// when a tool handle is no longer referenced.\nconst _validatorCache = new WeakMap<\n object,\n ReturnType<typeof _ajv.compile>\n>()\n\nfunction validateJsonSchema<T>(\n toolId: string,\n schema: Record<string, unknown>,\n value: unknown,\n): ValidationResult<T> {\n let validate = _validatorCache.get(schema)\n if (!validate) {\n validate = _ajv.compile(schema as Parameters<typeof _ajv.compile>[0])\n _validatorCache.set(schema, validate)\n }\n const valid = validate(value)\n if (!valid) {\n const errors = validate.errors ?? []\n const message = errors\n .map((e) => `${e.instancePath || \"/\"} ${e.message}`)\n .join(\"; \")\n return {\n ok: false,\n error: {\n code: \"input_invalid\",\n message: `id='${toolId}': ${message}`,\n cause: errors,\n },\n }\n }\n return { ok: true, value: value as T }\n}\n\nexport type { ZodType }\n","import matter from \"gray-matter\"\nimport { z, type ZodType } from \"zod\"\nimport { defineTool } from \"../define-tool.js\"\nimport type { ApprovalClass, ToolContext, ToolHandle } from \"../types.js\"\n\n/**\n * AIP-14 TOOL.md sidecar parser.\n *\n * Reads frontmatter (host-relevant metadata) + body (long-form\n * description / examples / errors). The TS module's `defineTool(...)`\n * supplies the schemas and execute body; this manifest supplies the\n * runtime metadata that overrides or augments the in-code defaults.\n *\n * Field set covers AIP-14 §\"Frontmatter\" — required and optional fields\n * normalised to snake_case → camelCase.\n */\n\nexport const toolManifestFrontmatterSchema = z.object({\n schema: z.literal(\"agentproto/tool/v1\").optional(),\n name: z.string().min(1).max(80),\n id: z.string().regex(/^[a-z][a-z0-9._-]{1,63}$/),\n description: z.string().min(1).max(2000),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+/),\n\n // Optional metadata\n mutates: z.array(z.string()).optional(),\n requires: z\n .object({\n network: z.array(z.string()).optional(),\n secrets: z.array(z.string()).optional(),\n tools: z.array(z.string()).optional(),\n })\n .optional(),\n // `ApprovalClass` is `\"auto\" | \"always\" | \"on-mutate\" | \\`policy:${string}\\``.\n // z.union widens the regex branch to plain `string` (zod can't express\n // template literal types), so we use `z.custom` to keep the inferred\n // type exact — matters because `defineTool` accepts `ApprovalClass`.\n approval: z\n .custom<ApprovalClass>(\n (v): v is ApprovalClass =>\n typeof v === \"string\" &&\n (v === \"auto\" ||\n v === \"always\" ||\n v === \"on-mutate\" ||\n /^policy:/.test(v)),\n { message: \"expected 'auto' | 'always' | 'on-mutate' | 'policy:<name>'\" },\n )\n .optional(),\n risk_level: z\n .union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)])\n .optional(),\n cost_class: z.enum([\"trivial\", \"metered\", \"expensive\"]).optional(),\n timeout_ms: z.number().int().positive().optional(),\n idempotent: z.boolean().optional(),\n tags: z.array(z.string()).optional(),\n metadata: z.record(z.string(), z.unknown()).optional(),\n\n // AIP-16 IO blocks — `inputs`/`outputs` as JSON Schema objects. Kept\n // structurally loose here (validated as objects, not deep-checked against\n // the AIP-16 meta-schema); preserved so a manifest's declared IO contract\n // survives the parse → handle round-trip instead of being silently dropped.\n inputs: z.record(z.string(), z.unknown()).optional(),\n outputs: z.record(z.string(), z.unknown()).optional(),\n\n // AIP-26 / AIP-17 / AIP-19 references — kept loose; validated by their\n // respective AIPs' adapters when consumed.\n code: z.unknown().optional(),\n run: z.unknown().optional(),\n runner: z.unknown().optional(),\n secrets: z.unknown().optional(),\n network: z.unknown().optional(),\n})\n\nexport type ToolManifestFrontmatter = z.infer<\n typeof toolManifestFrontmatterSchema\n>\n\nexport interface ToolManifest {\n frontmatter: ToolManifestFrontmatter\n body: string\n}\n\n/**\n * Parse a TOOL.md source string into structured frontmatter + body.\n * Throws on missing frontmatter or schema-invalid frontmatter.\n */\nexport function parseToolManifest(source: string): ToolManifest {\n const parsed = matter(source)\n if (Object.keys(parsed.data).length === 0) {\n throw new Error(\"parseToolManifest: missing or empty frontmatter\")\n }\n const result = toolManifestFrontmatterSchema.safeParse(parsed.data)\n if (!result.success) {\n throw new Error(\n `parseToolManifest: invalid frontmatter — ${result.error.issues\n .map(i => `${i.path.join(\".\")}: ${i.message}`)\n .join(\"; \")}`\n )\n }\n return { frontmatter: result.data, body: parsed.content }\n}\n\n/**\n * Build a {@link ToolHandle} from a manifest that has no companion TS module.\n *\n * `inputSchema`/`outputSchema` are omitted; IO validation falls back to the\n * AIP-16 `inputs`/`outputs` JSON Schema blocks declared in the frontmatter\n * (via `validateInput`/`validateOutput`). The returned handle is typed as\n * `ToolHandle<unknown, unknown>` since the generic shapes are not statically\n * known.\n *\n * Use this when loading an agent-generated TOOL.md whose IO contract is\n * expressed in YAML (`inputs:`/`outputs:`) rather than a compiled TS module.\n */\nexport function toolFromManifestOnly(\n manifest: ToolManifest,\n): ToolHandle<unknown, unknown> {\n const fm = manifest.frontmatter\n return defineTool({\n id: fm.id,\n name: fm.name,\n description: fm.description,\n version: fm.version,\n inputs: fm.inputs,\n outputs: fm.outputs,\n mutates: fm.mutates,\n requires: fm.requires,\n approval: fm.approval,\n riskLevel: fm.risk_level,\n costClass: fm.cost_class,\n timeoutMs: fm.timeout_ms,\n idempotent: fm.idempotent,\n tags: fm.tags,\n metadata: fm.metadata,\n })\n}\n\n/**\n * Build a fully-typed {@link ToolHandle} from a parsed `TOOL.md` manifest\n * + caller-supplied schemas. The .md is the single source of truth for\n * metadata (id, name, description, version, mutates, approval, …); the\n * schemas live in the TS module that ships alongside the .md.\n *\n * Both inputs are revalidated by `defineTool`'s shared invariants\n * (id pattern, description length, top-level freeze) — `parseToolManifest`\n * already enforces a stricter id pattern + version semver, so a\n * well-formed manifest passes through cleanly. Mismatches between the\n * manifest's id-shape and `defineTool`'s pattern surface a\n * descriptive error from the same validation pipeline as the TS path.\n *\n * @example\n * const manifest = parseToolManifest(readFileSync(\"./echo/TOOL.md\", \"utf8\"))\n * const echo = toolFromManifest({\n * manifest,\n * inputSchema: z.object({ msg: z.string() }),\n * outputSchema: z.object({ msg: z.string() }),\n * })\n */\nexport function toolFromManifest<\n TInput,\n TOutput,\n TContext extends ToolContext = ToolContext,\n>(args: {\n manifest: ToolManifest\n inputSchema: ZodType<TInput>\n outputSchema: ZodType<TOutput>\n contextSchema?: ZodType<TContext>\n}): ToolHandle<TInput, TOutput, TContext> {\n const fm = args.manifest.frontmatter\n return defineTool<TInput, TOutput, TContext>({\n id: fm.id,\n name: fm.name,\n description: fm.description,\n version: fm.version,\n inputSchema: args.inputSchema,\n outputSchema: args.outputSchema,\n inputs: fm.inputs,\n outputs: fm.outputs,\n contextSchema: args.contextSchema,\n mutates: fm.mutates,\n requires: fm.requires,\n approval: fm.approval,\n riskLevel: fm.risk_level,\n costClass: fm.cost_class,\n timeoutMs: fm.timeout_ms,\n idempotent: fm.idempotent,\n tags: fm.tags,\n metadata: fm.metadata,\n })\n}\n"]}