@contractspec/lib.ai-agent 1.44.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/LICENSE +21 -0
- package/README.md +49 -0
- package/dist/agent/agent-factory.d.ts +104 -0
- package/dist/agent/agent-factory.d.ts.map +1 -0
- package/dist/agent/agent-factory.js +103 -0
- package/dist/agent/agent-factory.js.map +1 -0
- package/dist/agent/contract-spec-agent.d.ts +75 -0
- package/dist/agent/contract-spec-agent.d.ts.map +1 -0
- package/dist/agent/contract-spec-agent.js +148 -0
- package/dist/agent/contract-spec-agent.js.map +1 -0
- package/dist/agent/index.d.ts +3 -0
- package/dist/agent/index.js +4 -0
- package/dist/approval/index.d.ts +2 -0
- package/dist/approval/index.js +3 -0
- package/dist/approval/workflow.d.ts +156 -0
- package/dist/approval/workflow.d.ts.map +1 -0
- package/dist/approval/workflow.js +160 -0
- package/dist/approval/workflow.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +21 -0
- package/dist/knowledge/index.d.ts +2 -0
- package/dist/knowledge/index.js +3 -0
- package/dist/knowledge/injector.d.ts +38 -0
- package/dist/knowledge/injector.d.ts.map +1 -0
- package/dist/knowledge/injector.js +58 -0
- package/dist/knowledge/injector.js.map +1 -0
- package/dist/memory/in-memory.d.ts +22 -0
- package/dist/memory/in-memory.d.ts.map +1 -0
- package/dist/memory/in-memory.js +48 -0
- package/dist/memory/in-memory.js.map +1 -0
- package/dist/memory/index.d.ts +3 -0
- package/dist/memory/index.js +4 -0
- package/dist/memory/manager.d.ts +42 -0
- package/dist/memory/manager.d.ts.map +1 -0
- package/dist/memory/manager.js +80 -0
- package/dist/memory/manager.js.map +1 -0
- package/dist/schema/index.d.ts +3 -0
- package/dist/schema/index.js +4 -0
- package/dist/schema/json-schema-to-zod.d.ts +55 -0
- package/dist/schema/json-schema-to-zod.d.ts.map +1 -0
- package/dist/schema/json-schema-to-zod.js +124 -0
- package/dist/schema/json-schema-to-zod.js.map +1 -0
- package/dist/schema/schema-output.d.ts +77 -0
- package/dist/schema/schema-output.d.ts.map +1 -0
- package/dist/schema/schema-output.js +65 -0
- package/dist/schema/schema-output.js.map +1 -0
- package/dist/session/index.d.ts +2 -0
- package/dist/session/index.js +3 -0
- package/dist/session/store.d.ts +74 -0
- package/dist/session/store.d.ts.map +1 -0
- package/dist/session/store.js +79 -0
- package/dist/session/store.js.map +1 -0
- package/dist/spec/index.d.ts +3 -0
- package/dist/spec/index.js +4 -0
- package/dist/spec/registry.d.ts +78 -0
- package/dist/spec/registry.d.ts.map +1 -0
- package/dist/spec/registry.js +117 -0
- package/dist/spec/registry.js.map +1 -0
- package/dist/spec/spec.d.ts +127 -0
- package/dist/spec/spec.d.ts.map +1 -0
- package/dist/spec/spec.js +30 -0
- package/dist/spec/spec.js.map +1 -0
- package/dist/telemetry/adapter.d.ts +73 -0
- package/dist/telemetry/adapter.d.ts.map +1 -0
- package/dist/telemetry/adapter.js +103 -0
- package/dist/telemetry/adapter.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/tools/index.d.ts +5 -0
- package/dist/tools/index.js +6 -0
- package/dist/tools/knowledge-tool.d.ts +21 -0
- package/dist/tools/knowledge-tool.d.ts.map +1 -0
- package/dist/tools/knowledge-tool.js +54 -0
- package/dist/tools/knowledge-tool.js.map +1 -0
- package/dist/tools/mcp-client.d.ts +59 -0
- package/dist/tools/mcp-client.d.ts.map +1 -0
- package/dist/tools/mcp-client.js +58 -0
- package/dist/tools/mcp-client.js.map +1 -0
- package/dist/tools/mcp-server.d.ts +46 -0
- package/dist/tools/mcp-server.d.ts.map +1 -0
- package/dist/tools/mcp-server.js +69 -0
- package/dist/tools/mcp-server.js.map +1 -0
- package/dist/tools/tool-adapter.d.ts +50 -0
- package/dist/tools/tool-adapter.d.ts.map +1 -0
- package/dist/tools/tool-adapter.js +80 -0
- package/dist/tools/tool-adapter.js.map +1 -0
- package/dist/types.d.ts +146 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +0 -0
- package/package.json +114 -0
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { tool } from "ai";
|
|
2
|
+
import * as z$1 from "zod";
|
|
3
|
+
|
|
4
|
+
//#region src/tools/knowledge-tool.ts
|
|
5
|
+
/**
|
|
6
|
+
* Create a knowledge query tool for dynamic RAG.
|
|
7
|
+
*
|
|
8
|
+
* This tool allows the agent to query optional knowledge spaces
|
|
9
|
+
* at runtime. Required knowledge is injected statically via
|
|
10
|
+
* the knowledge injector.
|
|
11
|
+
*
|
|
12
|
+
* @param retriever - The knowledge retriever to use
|
|
13
|
+
* @param knowledgeRefs - Knowledge references from the agent spec
|
|
14
|
+
* @returns AI SDK CoreTool for knowledge queries
|
|
15
|
+
*/
|
|
16
|
+
function createKnowledgeQueryTool(retriever, knowledgeRefs) {
|
|
17
|
+
const optionalSpaces = knowledgeRefs.filter((k) => !k.required).map((k) => k.key).filter((key) => retriever.supportsSpace(key));
|
|
18
|
+
if (optionalSpaces.length === 0) return null;
|
|
19
|
+
return tool({
|
|
20
|
+
description: `Query knowledge bases for relevant information. Use this tool when you need to look up specific information that may not be in your context.
|
|
21
|
+
|
|
22
|
+
Available knowledge spaces:
|
|
23
|
+
${knowledgeRefs.filter((k) => !k.required && retriever.supportsSpace(k.key)).map((k) => `- ${k.key}: ${k.instructions ?? "Knowledge space"}`).join("\n")}`,
|
|
24
|
+
inputSchema: z$1.object({
|
|
25
|
+
query: z$1.string().describe("The question or search query to find relevant information"),
|
|
26
|
+
spaceKey: z$1.enum(optionalSpaces).optional().describe("Specific knowledge space to query. If omitted, searches all available spaces."),
|
|
27
|
+
topK: z$1.number().optional().default(5).describe("Maximum number of results to return")
|
|
28
|
+
}),
|
|
29
|
+
execute: async ({ query, spaceKey, topK }) => {
|
|
30
|
+
const spacesToSearch = spaceKey ? [spaceKey] : optionalSpaces;
|
|
31
|
+
const allResults = [];
|
|
32
|
+
for (const space of spacesToSearch) try {
|
|
33
|
+
const results = await retriever.retrieve(query, {
|
|
34
|
+
spaceKey: space,
|
|
35
|
+
topK: topK ?? 5
|
|
36
|
+
});
|
|
37
|
+
for (const result of results) allResults.push({
|
|
38
|
+
space,
|
|
39
|
+
content: result.content,
|
|
40
|
+
score: result.score
|
|
41
|
+
});
|
|
42
|
+
} catch (error) {
|
|
43
|
+
console.warn(`Failed to query knowledge space ${space}:`, error);
|
|
44
|
+
}
|
|
45
|
+
if (allResults.length === 0) return "No relevant information found in the knowledge bases.";
|
|
46
|
+
allResults.sort((a, b) => b.score - a.score);
|
|
47
|
+
return allResults.slice(0, topK ?? 5).map((r, i) => `[Source ${i + 1} - ${r.space}] (relevance: ${(r.score * 100).toFixed(0)}%)\n${r.content}`).join("\n\n---\n\n");
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
//#endregion
|
|
53
|
+
export { createKnowledgeQueryTool };
|
|
54
|
+
//# sourceMappingURL=knowledge-tool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"knowledge-tool.js","names":["z","allResults: { space: string; content: string; score: number }[]"],"sources":["../../src/tools/knowledge-tool.ts"],"sourcesContent":["import { tool, type Tool } from 'ai';\nimport * as z from 'zod';\nimport type { KnowledgeRetriever } from '@contractspec/lib.knowledge/retriever';\nimport type { AgentKnowledgeRef } from '../spec/spec';\n\n/**\n * Create a knowledge query tool for dynamic RAG.\n *\n * This tool allows the agent to query optional knowledge spaces\n * at runtime. Required knowledge is injected statically via\n * the knowledge injector.\n *\n * @param retriever - The knowledge retriever to use\n * @param knowledgeRefs - Knowledge references from the agent spec\n * @returns AI SDK CoreTool for knowledge queries\n */\nexport function createKnowledgeQueryTool(\n retriever: KnowledgeRetriever,\n knowledgeRefs: AgentKnowledgeRef[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Tool<any, any> | null {\n // Only include optional (non-required) knowledge spaces\n const optionalSpaces = knowledgeRefs\n .filter((k) => !k.required)\n .map((k) => k.key)\n .filter((key) => retriever.supportsSpace(key));\n\n if (optionalSpaces.length === 0) {\n return null;\n }\n\n // Build space descriptions for the tool\n const spaceDescriptions = knowledgeRefs\n .filter((k) => !k.required && retriever.supportsSpace(k.key))\n .map((k) => `- ${k.key}: ${k.instructions ?? 'Knowledge space'}`)\n .join('\\n');\n\n return tool({\n description: `Query knowledge bases for relevant information. Use this tool when you need to look up specific information that may not be in your context.\n\nAvailable knowledge spaces:\n${spaceDescriptions}`,\n // AI SDK v6 uses inputSchema instead of parameters\n inputSchema: z.object({\n query: z\n .string()\n .describe('The question or search query to find relevant information'),\n spaceKey: z\n .enum(optionalSpaces as [string, ...string[]])\n .optional()\n .describe(\n 'Specific knowledge space to query. If omitted, searches all available spaces.'\n ),\n topK: z\n .number()\n .optional()\n .default(5)\n .describe('Maximum number of results to return'),\n }),\n execute: async ({ query, spaceKey, topK }) => {\n const spacesToSearch = spaceKey ? [spaceKey] : optionalSpaces;\n const allResults: { space: string; content: string; score: number }[] =\n [];\n\n for (const space of spacesToSearch) {\n try {\n const results = await retriever.retrieve(query, {\n spaceKey: space,\n topK: topK ?? 5,\n });\n\n for (const result of results) {\n allResults.push({\n space,\n content: result.content,\n score: result.score,\n });\n }\n } catch (error) {\n // Log but don't fail on individual space errors\n console.warn(`Failed to query knowledge space ${space}:`, error);\n }\n }\n\n if (allResults.length === 0) {\n return 'No relevant information found in the knowledge bases.';\n }\n\n // Sort by score and format results\n allResults.sort((a, b) => b.score - a.score);\n const topResults = allResults.slice(0, topK ?? 5);\n\n return topResults\n .map(\n (r, i) =>\n `[Source ${i + 1} - ${r.space}] (relevance: ${(r.score * 100).toFixed(0)}%)\\n${r.content}`\n )\n .join('\\n\\n---\\n\\n');\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,SAAgB,yBACd,WACA,eAEuB;CAEvB,MAAM,iBAAiB,cACpB,QAAQ,MAAM,CAAC,EAAE,SAAS,CAC1B,KAAK,MAAM,EAAE,IAAI,CACjB,QAAQ,QAAQ,UAAU,cAAc,IAAI,CAAC;AAEhD,KAAI,eAAe,WAAW,EAC5B,QAAO;AAST,QAAO,KAAK;EACV,aAAa;;;EANW,cACvB,QAAQ,MAAM,CAAC,EAAE,YAAY,UAAU,cAAc,EAAE,IAAI,CAAC,CAC5D,KAAK,MAAM,KAAK,EAAE,IAAI,IAAI,EAAE,gBAAgB,oBAAoB,CAChE,KAAK,KAAK;EAQX,aAAaA,IAAE,OAAO;GACpB,OAAOA,IACJ,QAAQ,CACR,SAAS,4DAA4D;GACxE,UAAUA,IACP,KAAK,eAAwC,CAC7C,UAAU,CACV,SACC,gFACD;GACH,MAAMA,IACH,QAAQ,CACR,UAAU,CACV,QAAQ,EAAE,CACV,SAAS,sCAAsC;GACnD,CAAC;EACF,SAAS,OAAO,EAAE,OAAO,UAAU,WAAW;GAC5C,MAAM,iBAAiB,WAAW,CAAC,SAAS,GAAG;GAC/C,MAAMC,aACJ,EAAE;AAEJ,QAAK,MAAM,SAAS,eAClB,KAAI;IACF,MAAM,UAAU,MAAM,UAAU,SAAS,OAAO;KAC9C,UAAU;KACV,MAAM,QAAQ;KACf,CAAC;AAEF,SAAK,MAAM,UAAU,QACnB,YAAW,KAAK;KACd;KACA,SAAS,OAAO;KAChB,OAAO,OAAO;KACf,CAAC;YAEG,OAAO;AAEd,YAAQ,KAAK,mCAAmC,MAAM,IAAI,MAAM;;AAIpE,OAAI,WAAW,WAAW,EACxB,QAAO;AAIT,cAAW,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM;AAG5C,UAFmB,WAAW,MAAM,GAAG,QAAQ,EAAE,CAG9C,KACE,GAAG,MACF,WAAW,IAAI,EAAE,KAAK,EAAE,MAAM,iBAAiB,EAAE,QAAQ,KAAK,QAAQ,EAAE,CAAC,MAAM,EAAE,UACpF,CACA,KAAK,cAAc;;EAEzB,CAAC"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Tool } from "ai";
|
|
2
|
+
|
|
3
|
+
//#region src/tools/mcp-client.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Configuration for connecting to an MCP server.
|
|
7
|
+
*/
|
|
8
|
+
interface McpClientConfig {
|
|
9
|
+
/** Display name for the MCP server */
|
|
10
|
+
name: string;
|
|
11
|
+
/** Command to spawn the MCP server process */
|
|
12
|
+
command: string;
|
|
13
|
+
/** Arguments to pass to the command */
|
|
14
|
+
args?: string[];
|
|
15
|
+
/** Environment variables for the process */
|
|
16
|
+
env?: Record<string, string>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Result of creating an MCP client with tools.
|
|
20
|
+
*/
|
|
21
|
+
interface McpClientResult {
|
|
22
|
+
/** AI SDK tools from the MCP server */
|
|
23
|
+
tools: Record<string, Tool<unknown, unknown>>;
|
|
24
|
+
/** Cleanup function to close the connection */
|
|
25
|
+
cleanup: () => Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Create AI SDK tools from an MCP server.
|
|
29
|
+
*
|
|
30
|
+
* This adapter allows ContractSpec agents to consume tools
|
|
31
|
+
* from external MCP servers (e.g., filesystem, database, etc.).
|
|
32
|
+
*
|
|
33
|
+
* @param config - MCP server configuration
|
|
34
|
+
* @returns Tools and cleanup function
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* const { tools, cleanup } = await mcpServerToTools({
|
|
39
|
+
* name: 'filesystem',
|
|
40
|
+
* command: 'npx',
|
|
41
|
+
* args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],
|
|
42
|
+
* });
|
|
43
|
+
*
|
|
44
|
+
* // Use tools in agent...
|
|
45
|
+
*
|
|
46
|
+
* await cleanup();
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
declare function mcpServerToTools(config: McpClientConfig): Promise<McpClientResult>;
|
|
50
|
+
/**
|
|
51
|
+
* Create multiple MCP tool sets from configurations.
|
|
52
|
+
*
|
|
53
|
+
* @param configs - Array of MCP server configurations
|
|
54
|
+
* @returns Combined tools and cleanup function
|
|
55
|
+
*/
|
|
56
|
+
declare function createMcpToolsets(configs: McpClientConfig[]): Promise<McpClientResult>;
|
|
57
|
+
//#endregion
|
|
58
|
+
export { McpClientConfig, McpClientResult, createMcpToolsets, mcpServerToTools };
|
|
59
|
+
//# sourceMappingURL=mcp-client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-client.d.ts","names":[],"sources":["../../src/tools/mcp-client.ts"],"sourcesContent":[],"mappings":";;;;;;AAOA;AAciB,UAdA,eAAA,CAce;EAER;EAAf,IAAA,EAAA,MAAA;EAEQ;EAAO,OAAA,EAAA,MAAA;EAyBF;EACZ,IAAA,CAAA,EAAA,MAAA,EAAA;EACC;EAAR,GAAA,CAAA,EArCK,MAqCL,CAAA,MAAA,EAAA,MAAA,CAAA;;AAsBH;;;AAEG,UAvDc,eAAA,CAuDd;EAAO;SArDD,eAAe;;iBAEP;;;;;;;;;;;;;;;;;;;;;;;;iBAyBK,gBAAA,SACZ,kBACP,QAAQ;;;;;;;iBAsBW,iBAAA,UACX,oBACR,QAAQ"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { experimental_createMCPClient } from "@ai-sdk/mcp";
|
|
2
|
+
import { Experimental_StdioMCPTransport } from "@ai-sdk/mcp/mcp-stdio";
|
|
3
|
+
|
|
4
|
+
//#region src/tools/mcp-client.ts
|
|
5
|
+
/**
|
|
6
|
+
* Create AI SDK tools from an MCP server.
|
|
7
|
+
*
|
|
8
|
+
* This adapter allows ContractSpec agents to consume tools
|
|
9
|
+
* from external MCP servers (e.g., filesystem, database, etc.).
|
|
10
|
+
*
|
|
11
|
+
* @param config - MCP server configuration
|
|
12
|
+
* @returns Tools and cleanup function
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* const { tools, cleanup } = await mcpServerToTools({
|
|
17
|
+
* name: 'filesystem',
|
|
18
|
+
* command: 'npx',
|
|
19
|
+
* args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* // Use tools in agent...
|
|
23
|
+
*
|
|
24
|
+
* await cleanup();
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
async function mcpServerToTools(config) {
|
|
28
|
+
const client = await experimental_createMCPClient({ transport: new Experimental_StdioMCPTransport({
|
|
29
|
+
command: config.command,
|
|
30
|
+
args: config.args,
|
|
31
|
+
env: config.env
|
|
32
|
+
}) });
|
|
33
|
+
return {
|
|
34
|
+
tools: await client.tools(),
|
|
35
|
+
cleanup: () => client.close()
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Create multiple MCP tool sets from configurations.
|
|
40
|
+
*
|
|
41
|
+
* @param configs - Array of MCP server configurations
|
|
42
|
+
* @returns Combined tools and cleanup function
|
|
43
|
+
*/
|
|
44
|
+
async function createMcpToolsets(configs) {
|
|
45
|
+
const results = await Promise.all(configs.map(mcpServerToTools));
|
|
46
|
+
const combinedTools = {};
|
|
47
|
+
for (const result of results) Object.assign(combinedTools, result.tools);
|
|
48
|
+
return {
|
|
49
|
+
tools: combinedTools,
|
|
50
|
+
cleanup: async () => {
|
|
51
|
+
await Promise.all(results.map((r) => r.cleanup()));
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
//#endregion
|
|
57
|
+
export { createMcpToolsets, mcpServerToTools };
|
|
58
|
+
//# sourceMappingURL=mcp-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-client.js","names":["StdioClientTransport","combinedTools: Record<string, Tool<unknown, unknown>>"],"sources":["../../src/tools/mcp-client.ts"],"sourcesContent":["import { experimental_createMCPClient } from '@ai-sdk/mcp';\nimport { Experimental_StdioMCPTransport as StdioClientTransport } from '@ai-sdk/mcp/mcp-stdio';\nimport type { Tool } from 'ai';\n\n/**\n * Configuration for connecting to an MCP server.\n */\nexport interface McpClientConfig {\n /** Display name for the MCP server */\n name: string;\n /** Command to spawn the MCP server process */\n command: string;\n /** Arguments to pass to the command */\n args?: string[];\n /** Environment variables for the process */\n env?: Record<string, string>;\n}\n\n/**\n * Result of creating an MCP client with tools.\n */\nexport interface McpClientResult {\n /** AI SDK tools from the MCP server */\n tools: Record<string, Tool<unknown, unknown>>;\n /** Cleanup function to close the connection */\n cleanup: () => Promise<void>;\n}\n\n/**\n * Create AI SDK tools from an MCP server.\n *\n * This adapter allows ContractSpec agents to consume tools\n * from external MCP servers (e.g., filesystem, database, etc.).\n *\n * @param config - MCP server configuration\n * @returns Tools and cleanup function\n *\n * @example\n * ```typescript\n * const { tools, cleanup } = await mcpServerToTools({\n * name: 'filesystem',\n * command: 'npx',\n * args: ['-y', '@modelcontextprotocol/server-filesystem', '/path'],\n * });\n *\n * // Use tools in agent...\n *\n * await cleanup();\n * ```\n */\nexport async function mcpServerToTools(\n config: McpClientConfig\n): Promise<McpClientResult> {\n const transport = new StdioClientTransport({\n command: config.command,\n args: config.args,\n env: config.env,\n });\n\n const client = await experimental_createMCPClient({ transport });\n const tools = await client.tools();\n\n return {\n tools: tools as Record<string, Tool<unknown, unknown>>,\n cleanup: () => client.close(),\n };\n}\n\n/**\n * Create multiple MCP tool sets from configurations.\n *\n * @param configs - Array of MCP server configurations\n * @returns Combined tools and cleanup function\n */\nexport async function createMcpToolsets(\n configs: McpClientConfig[]\n): Promise<McpClientResult> {\n const results = await Promise.all(configs.map(mcpServerToTools));\n\n const combinedTools: Record<string, Tool<unknown, unknown>> = {};\n for (const result of results) {\n Object.assign(combinedTools, result.tools);\n }\n\n return {\n tools: combinedTools,\n cleanup: async () => {\n await Promise.all(results.map((r) => r.cleanup()));\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,eAAsB,iBACpB,QAC0B;CAO1B,MAAM,SAAS,MAAM,6BAA6B,EAAE,WANlC,IAAIA,+BAAqB;EACzC,SAAS,OAAO;EAChB,MAAM,OAAO;EACb,KAAK,OAAO;EACb,CAAC,EAE6D,CAAC;AAGhE,QAAO;EACL,OAHY,MAAM,OAAO,OAAO;EAIhC,eAAe,OAAO,OAAO;EAC9B;;;;;;;;AASH,eAAsB,kBACpB,SAC0B;CAC1B,MAAM,UAAU,MAAM,QAAQ,IAAI,QAAQ,IAAI,iBAAiB,CAAC;CAEhE,MAAMC,gBAAwD,EAAE;AAChE,MAAK,MAAM,UAAU,QACnB,QAAO,OAAO,eAAe,OAAO,MAAM;AAG5C,QAAO;EACL,OAAO;EACP,SAAS,YAAY;AACnB,SAAM,QAAQ,IAAI,QAAQ,KAAK,MAAM,EAAE,SAAS,CAAC,CAAC;;EAErD"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { AgentSpec } from "../spec/spec.js";
|
|
2
|
+
import { ContractSpecAgent } from "../agent/contract-spec-agent.js";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
|
|
5
|
+
//#region src/tools/mcp-server.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Generate an MCP server that exposes a ContractSpec agent as a tool.
|
|
9
|
+
*
|
|
10
|
+
* This allows other AI agents (e.g., Claude Desktop, Cursor) to use
|
|
11
|
+
* your ContractSpec agents as tools, enabling agent-to-agent composition.
|
|
12
|
+
*
|
|
13
|
+
* @param agent - The ContractSpec agent to expose
|
|
14
|
+
* @param spec - The agent specification
|
|
15
|
+
* @returns MCP Server instance
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* const server = agentToMcpServer(myAgent, myAgentSpec);
|
|
20
|
+
*
|
|
21
|
+
* // Run via stdio transport
|
|
22
|
+
* const transport = new StdioServerTransport();
|
|
23
|
+
* await server.connect(transport);
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
declare function agentToMcpServer(agent: ContractSpecAgent, spec: AgentSpec): McpServer;
|
|
27
|
+
/**
|
|
28
|
+
* Configuration for running an agent as an MCP server.
|
|
29
|
+
*/
|
|
30
|
+
interface AgentMcpServerConfig {
|
|
31
|
+
/** The agent to expose */
|
|
32
|
+
agent: ContractSpecAgent;
|
|
33
|
+
/** The agent specification */
|
|
34
|
+
spec: AgentSpec;
|
|
35
|
+
/** Optional server name override */
|
|
36
|
+
name?: string;
|
|
37
|
+
/** Optional version override */
|
|
38
|
+
version?: string;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Create an MCP server from configuration.
|
|
42
|
+
*/
|
|
43
|
+
declare function createAgentMcpServer(config: AgentMcpServerConfig): McpServer;
|
|
44
|
+
//#endregion
|
|
45
|
+
export { AgentMcpServerConfig, agentToMcpServer, createAgentMcpServer };
|
|
46
|
+
//# sourceMappingURL=mcp-server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-server.d.ts","names":[],"sources":["../../src/tools/mcp-server.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAyBA;;;;;AA+EA;AAcA;;;;;;;;;;;iBA7FgB,gBAAA,QACP,yBACD,YACL;;;;UA4Ec,oBAAA;;SAER;;QAED;;;;;;;;;iBAUQ,oBAAA,SAA6B,uBAAuB"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { jsonSchemaToZodSafe } from "../schema/json-schema-to-zod.js";
|
|
2
|
+
import * as z$1 from "zod";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
|
|
5
|
+
//#region src/tools/mcp-server.ts
|
|
6
|
+
/**
|
|
7
|
+
* Generate an MCP server that exposes a ContractSpec agent as a tool.
|
|
8
|
+
*
|
|
9
|
+
* This allows other AI agents (e.g., Claude Desktop, Cursor) to use
|
|
10
|
+
* your ContractSpec agents as tools, enabling agent-to-agent composition.
|
|
11
|
+
*
|
|
12
|
+
* @param agent - The ContractSpec agent to expose
|
|
13
|
+
* @param spec - The agent specification
|
|
14
|
+
* @returns MCP Server instance
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* const server = agentToMcpServer(myAgent, myAgentSpec);
|
|
19
|
+
*
|
|
20
|
+
* // Run via stdio transport
|
|
21
|
+
* const transport = new StdioServerTransport();
|
|
22
|
+
* await server.connect(transport);
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
function agentToMcpServer(agent, spec) {
|
|
26
|
+
const server = new McpServer({
|
|
27
|
+
name: spec.meta.key,
|
|
28
|
+
version: `${spec.meta.version}`
|
|
29
|
+
});
|
|
30
|
+
server.registerTool(spec.meta.key, {
|
|
31
|
+
description: spec.description ?? `Interact with ${spec.meta.key} agent`,
|
|
32
|
+
inputSchema: z$1.object({
|
|
33
|
+
message: z$1.string().describe("The message or query to send to the agent"),
|
|
34
|
+
sessionId: z$1.string().optional().describe("Optional session ID to continue a conversation")
|
|
35
|
+
})
|
|
36
|
+
}, async (args) => {
|
|
37
|
+
const { message, sessionId } = args;
|
|
38
|
+
return { content: [{
|
|
39
|
+
type: "text",
|
|
40
|
+
text: (await agent.generate({
|
|
41
|
+
prompt: message,
|
|
42
|
+
options: { sessionId }
|
|
43
|
+
})).text
|
|
44
|
+
}] };
|
|
45
|
+
});
|
|
46
|
+
for (const toolConfig of spec.tools) {
|
|
47
|
+
const inputSchema = toolConfig.schema ? jsonSchemaToZodSafe(toolConfig.schema) : z$1.object({});
|
|
48
|
+
server.registerTool(`${spec.meta.key}.${toolConfig.name}`, {
|
|
49
|
+
description: toolConfig.description ?? `Execute ${toolConfig.name} tool`,
|
|
50
|
+
inputSchema
|
|
51
|
+
}, async (args) => {
|
|
52
|
+
return { content: [{
|
|
53
|
+
type: "text",
|
|
54
|
+
text: (await agent.generate({ prompt: `Execute the ${toolConfig.name} tool with the following arguments: ${JSON.stringify(args)}` })).text
|
|
55
|
+
}] };
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
return server;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Create an MCP server from configuration.
|
|
62
|
+
*/
|
|
63
|
+
function createAgentMcpServer(config) {
|
|
64
|
+
return agentToMcpServer(config.agent, config.spec);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
//#endregion
|
|
68
|
+
export { agentToMcpServer, createAgentMcpServer };
|
|
69
|
+
//# sourceMappingURL=mcp-server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mcp-server.js","names":["z"],"sources":["../../src/tools/mcp-server.ts"],"sourcesContent":["import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport * as z from 'zod';\nimport type { AgentSpec } from '../spec/spec';\nimport type { ContractSpecAgent } from '../agent/contract-spec-agent';\nimport { jsonSchemaToZodSafe } from '../schema/json-schema-to-zod';\n\n/**\n * Generate an MCP server that exposes a ContractSpec agent as a tool.\n *\n * This allows other AI agents (e.g., Claude Desktop, Cursor) to use\n * your ContractSpec agents as tools, enabling agent-to-agent composition.\n *\n * @param agent - The ContractSpec agent to expose\n * @param spec - The agent specification\n * @returns MCP Server instance\n *\n * @example\n * ```typescript\n * const server = agentToMcpServer(myAgent, myAgentSpec);\n *\n * // Run via stdio transport\n * const transport = new StdioServerTransport();\n * await server.connect(transport);\n * ```\n */\nexport function agentToMcpServer(\n agent: ContractSpecAgent,\n spec: AgentSpec\n): McpServer {\n const server = new McpServer({\n name: spec.meta.key,\n version: `${spec.meta.version}`,\n });\n\n // Expose agent as a conversational tool using registerTool\n server.registerTool(\n spec.meta.key,\n {\n description: spec.description ?? `Interact with ${spec.meta.key} agent`,\n inputSchema: z.object({\n message: z\n .string()\n .describe('The message or query to send to the agent'),\n sessionId: z\n .string()\n .optional()\n .describe('Optional session ID to continue a conversation'),\n }),\n },\n async (args) => {\n const { message, sessionId } = args;\n\n const result = await agent.generate({\n prompt: message,\n options: { sessionId },\n });\n\n return {\n content: [\n {\n type: 'text',\n text: result.text,\n },\n ],\n };\n }\n );\n\n // Expose individual tools from the agent spec\n for (const toolConfig of spec.tools) {\n const inputSchema = toolConfig.schema\n ? jsonSchemaToZodSafe(toolConfig.schema)\n : z.object({});\n\n server.registerTool(\n `${spec.meta.key}.${toolConfig.name}`,\n {\n description:\n toolConfig.description ?? `Execute ${toolConfig.name} tool`,\n inputSchema,\n },\n async (args) => {\n const result = await agent.generate({\n prompt: `Execute the ${toolConfig.name} tool with the following arguments: ${JSON.stringify(args)}`,\n });\n\n return {\n content: [\n {\n type: 'text',\n text: result.text,\n },\n ],\n };\n }\n );\n }\n\n return server;\n}\n\n/**\n * Configuration for running an agent as an MCP server.\n */\nexport interface AgentMcpServerConfig {\n /** The agent to expose */\n agent: ContractSpecAgent;\n /** The agent specification */\n spec: AgentSpec;\n /** Optional server name override */\n name?: string;\n /** Optional version override */\n version?: string;\n}\n\n/**\n * Create an MCP server from configuration.\n */\nexport function createAgentMcpServer(config: AgentMcpServerConfig): McpServer {\n return agentToMcpServer(config.agent, config.spec);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,iBACd,OACA,MACW;CACX,MAAM,SAAS,IAAI,UAAU;EAC3B,MAAM,KAAK,KAAK;EAChB,SAAS,GAAG,KAAK,KAAK;EACvB,CAAC;AAGF,QAAO,aACL,KAAK,KAAK,KACV;EACE,aAAa,KAAK,eAAe,iBAAiB,KAAK,KAAK,IAAI;EAChE,aAAaA,IAAE,OAAO;GACpB,SAASA,IACN,QAAQ,CACR,SAAS,4CAA4C;GACxD,WAAWA,IACR,QAAQ,CACR,UAAU,CACV,SAAS,iDAAiD;GAC9D,CAAC;EACH,EACD,OAAO,SAAS;EACd,MAAM,EAAE,SAAS,cAAc;AAO/B,SAAO,EACL,SAAS,CACP;GACE,MAAM;GACN,OATS,MAAM,MAAM,SAAS;IAClC,QAAQ;IACR,SAAS,EAAE,WAAW;IACvB,CAAC,EAMiB;GACd,CACF,EACF;GAEJ;AAGD,MAAK,MAAM,cAAc,KAAK,OAAO;EACnC,MAAM,cAAc,WAAW,SAC3B,oBAAoB,WAAW,OAAO,GACtCA,IAAE,OAAO,EAAE,CAAC;AAEhB,SAAO,aACL,GAAG,KAAK,KAAK,IAAI,GAAG,WAAW,QAC/B;GACE,aACE,WAAW,eAAe,WAAW,WAAW,KAAK;GACvD;GACD,EACD,OAAO,SAAS;AAKd,UAAO,EACL,SAAS,CACP;IACE,MAAM;IACN,OARS,MAAM,MAAM,SAAS,EAClC,QAAQ,eAAe,WAAW,KAAK,sCAAsC,KAAK,UAAU,KAAK,IAClG,CAAC,EAMiB;IACd,CACF,EACF;IAEJ;;AAGH,QAAO;;;;;AAoBT,SAAgB,qBAAqB,QAAyC;AAC5E,QAAO,iBAAiB,OAAO,OAAO,OAAO,KAAK"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { AgentToolConfig } from "../spec/spec.js";
|
|
2
|
+
import { ToolExecutionContext, ToolHandler } from "../types.js";
|
|
3
|
+
import { Tool } from "ai";
|
|
4
|
+
|
|
5
|
+
//#region src/tools/tool-adapter.d.ts
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Convert ContractSpec AgentToolConfig to AI SDK CoreTool.
|
|
9
|
+
*
|
|
10
|
+
* @param specTool - The tool configuration from AgentSpec
|
|
11
|
+
* @param handler - The handler function for the tool
|
|
12
|
+
* @param context - Partial context to inject into handler calls
|
|
13
|
+
* @returns AI SDK CoreTool
|
|
14
|
+
*/
|
|
15
|
+
declare function specToolToAISDKTool(specTool: AgentToolConfig, handler: ToolHandler, context?: Partial<ToolExecutionContext>): Tool<any, any>;
|
|
16
|
+
/**
|
|
17
|
+
* Convert multiple ContractSpec tool configs to AI SDK tools.
|
|
18
|
+
*
|
|
19
|
+
* @param specTools - Array of tool configurations
|
|
20
|
+
* @param handlers - Map of tool name to handler function
|
|
21
|
+
* @param context - Partial context to inject into handler calls
|
|
22
|
+
* @returns Record of AI SDK tools keyed by name
|
|
23
|
+
*/
|
|
24
|
+
declare function specToolsToAISDKTools(specTools: AgentToolConfig[], handlers: Map<string, ToolHandler>, context?: Partial<ToolExecutionContext>): Record<string, Tool<any, any>>;
|
|
25
|
+
/**
|
|
26
|
+
* Type-safe tool handler builder.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* const handler = createToolHandler<{ query: string }>((input, ctx) => {
|
|
31
|
+
* return `Searched for: ${input.query}`;
|
|
32
|
+
* });
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
declare function createToolHandler<TInput = unknown, TOutput = string>(handler: (input: TInput, context: ToolExecutionContext) => Promise<TOutput> | TOutput): ToolHandler<TInput, TOutput>;
|
|
36
|
+
/**
|
|
37
|
+
* Build a tool handlers map from an object.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```typescript
|
|
41
|
+
* const handlers = buildToolHandlers({
|
|
42
|
+
* search: async (input: { query: string }) => `Found: ${input.query}`,
|
|
43
|
+
* calculate: async (input: { a: number, b: number }) => `${input.a + input.b}`,
|
|
44
|
+
* });
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
declare function buildToolHandlers(handlersObj: Record<string, ToolHandler>): Map<string, ToolHandler>;
|
|
48
|
+
//#endregion
|
|
49
|
+
export { buildToolHandlers, createToolHandler, specToolToAISDKTool, specToolsToAISDKTools };
|
|
50
|
+
//# sourceMappingURL=tool-adapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-adapter.d.ts","names":[],"sources":["../../src/tools/tool-adapter.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAcA;;;;;;AAIO,iBAJS,mBAAA,CAIT,QAAA,EAHK,eAGL,EAAA,OAAA,EAFI,WAEJ,EAAA,OAAA,CAAA,EADI,OACJ,CADY,oBACZ,CAAA,CAAA,EAAJ,IAAI,CAAA,GAAA,EAAA,GAAA,CAAA;AA6BP;;;;;;;;AAIS,iBAJO,qBAAA,CAIP,SAAA,EAHI,eAGJ,EAAA,EAAA,QAAA,EAFG,GAEH,CAAA,MAAA,EAFe,WAEf,CAAA,EAAA,OAAA,CAAA,EADE,OACF,CADU,oBACV,CAAA,CAAA,EAAN,MAAM,CAAA,MAAA,EAAS,IAAT,CAAA,GAAA,EAAA,GAAA,CAAA,CAAA;AAyBT;;;;;;;;;;AAsBgB,iBAtBA,iBAsBiB,CAAA,SAAA,OAAA,EAAA,UAAA,MAAA,CAAA,CAAA,OAAA,EAAA,CAAA,KAAA,EApBtB,MAoBsB,EAAA,OAAA,EAnBpB,oBAmBoB,EAAA,GAlB1B,OAkB0B,CAlBlB,OAkBkB,CAAA,GAlBP,OAkBO,CAAA,EAjB9B,WAiB8B,CAjBlB,MAiBkB,EAjBV,OAiBU,CAAA;;;;;;;;;;;;iBAAjB,iBAAA,cACD,eAAe,eAC3B,YAAY"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { jsonSchemaToZodSafe } from "../schema/json-schema-to-zod.js";
|
|
2
|
+
import { tool } from "ai";
|
|
3
|
+
|
|
4
|
+
//#region src/tools/tool-adapter.ts
|
|
5
|
+
/**
|
|
6
|
+
* Convert ContractSpec AgentToolConfig to AI SDK CoreTool.
|
|
7
|
+
*
|
|
8
|
+
* @param specTool - The tool configuration from AgentSpec
|
|
9
|
+
* @param handler - The handler function for the tool
|
|
10
|
+
* @param context - Partial context to inject into handler calls
|
|
11
|
+
* @returns AI SDK CoreTool
|
|
12
|
+
*/
|
|
13
|
+
function specToolToAISDKTool(specTool, handler, context = {}) {
|
|
14
|
+
return tool({
|
|
15
|
+
description: specTool.description ?? specTool.name,
|
|
16
|
+
inputSchema: jsonSchemaToZodSafe(specTool.schema),
|
|
17
|
+
needsApproval: specTool.requiresApproval ?? !specTool.automationSafe,
|
|
18
|
+
execute: async (input) => {
|
|
19
|
+
const result = await handler(input, {
|
|
20
|
+
agentId: context.agentId ?? "unknown",
|
|
21
|
+
sessionId: context.sessionId ?? "unknown",
|
|
22
|
+
tenantId: context.tenantId,
|
|
23
|
+
actorId: context.actorId,
|
|
24
|
+
metadata: context.metadata,
|
|
25
|
+
signal: context.signal
|
|
26
|
+
});
|
|
27
|
+
return typeof result === "string" ? result : JSON.stringify(result);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Convert multiple ContractSpec tool configs to AI SDK tools.
|
|
33
|
+
*
|
|
34
|
+
* @param specTools - Array of tool configurations
|
|
35
|
+
* @param handlers - Map of tool name to handler function
|
|
36
|
+
* @param context - Partial context to inject into handler calls
|
|
37
|
+
* @returns Record of AI SDK tools keyed by name
|
|
38
|
+
*/
|
|
39
|
+
function specToolsToAISDKTools(specTools, handlers, context = {}) {
|
|
40
|
+
const tools = {};
|
|
41
|
+
for (const specTool of specTools) {
|
|
42
|
+
const handler = handlers.get(specTool.name);
|
|
43
|
+
if (!handler) throw new Error(`Missing handler for tool: ${specTool.name}`);
|
|
44
|
+
tools[specTool.name] = specToolToAISDKTool(specTool, handler, context);
|
|
45
|
+
}
|
|
46
|
+
return tools;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Type-safe tool handler builder.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```typescript
|
|
53
|
+
* const handler = createToolHandler<{ query: string }>((input, ctx) => {
|
|
54
|
+
* return `Searched for: ${input.query}`;
|
|
55
|
+
* });
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
function createToolHandler(handler) {
|
|
59
|
+
return async (input, context) => {
|
|
60
|
+
return handler(input, context);
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Build a tool handlers map from an object.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```typescript
|
|
68
|
+
* const handlers = buildToolHandlers({
|
|
69
|
+
* search: async (input: { query: string }) => `Found: ${input.query}`,
|
|
70
|
+
* calculate: async (input: { a: number, b: number }) => `${input.a + input.b}`,
|
|
71
|
+
* });
|
|
72
|
+
* ```
|
|
73
|
+
*/
|
|
74
|
+
function buildToolHandlers(handlersObj) {
|
|
75
|
+
return new Map(Object.entries(handlersObj));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
//#endregion
|
|
79
|
+
export { buildToolHandlers, createToolHandler, specToolToAISDKTool, specToolsToAISDKTools };
|
|
80
|
+
//# sourceMappingURL=tool-adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-adapter.js","names":["tools: Record<string, Tool<any, any>>"],"sources":["../../src/tools/tool-adapter.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { tool, type Tool } from 'ai';\nimport type { AgentToolConfig } from '../spec/spec';\nimport type { ToolExecutionContext, ToolHandler } from '../types';\nimport { jsonSchemaToZodSafe } from '../schema/json-schema-to-zod';\n\n/**\n * Convert ContractSpec AgentToolConfig to AI SDK CoreTool.\n *\n * @param specTool - The tool configuration from AgentSpec\n * @param handler - The handler function for the tool\n * @param context - Partial context to inject into handler calls\n * @returns AI SDK CoreTool\n */\nexport function specToolToAISDKTool(\n specTool: AgentToolConfig,\n handler: ToolHandler,\n context: Partial<ToolExecutionContext> = {}\n): Tool<any, any> {\n return tool({\n description: specTool.description ?? specTool.name,\n // AI SDK v6 uses inputSchema instead of parameters\n inputSchema: jsonSchemaToZodSafe(specTool.schema),\n // AI SDK v6 native approval support\n needsApproval: specTool.requiresApproval ?? !specTool.automationSafe,\n execute: async (input) => {\n const result = await handler(input, {\n agentId: context.agentId ?? 'unknown',\n sessionId: context.sessionId ?? 'unknown',\n tenantId: context.tenantId,\n actorId: context.actorId,\n metadata: context.metadata,\n signal: context.signal,\n });\n return typeof result === 'string' ? result : JSON.stringify(result);\n },\n });\n}\n\n/**\n * Convert multiple ContractSpec tool configs to AI SDK tools.\n *\n * @param specTools - Array of tool configurations\n * @param handlers - Map of tool name to handler function\n * @param context - Partial context to inject into handler calls\n * @returns Record of AI SDK tools keyed by name\n */\nexport function specToolsToAISDKTools(\n specTools: AgentToolConfig[],\n handlers: Map<string, ToolHandler>,\n context: Partial<ToolExecutionContext> = {}\n): Record<string, Tool<any, any>> {\n const tools: Record<string, Tool<any, any>> = {};\n\n for (const specTool of specTools) {\n const handler = handlers.get(specTool.name);\n if (!handler) {\n throw new Error(`Missing handler for tool: ${specTool.name}`);\n }\n\n tools[specTool.name] = specToolToAISDKTool(specTool, handler, context);\n }\n\n return tools;\n}\n\n/**\n * Type-safe tool handler builder.\n *\n * @example\n * ```typescript\n * const handler = createToolHandler<{ query: string }>((input, ctx) => {\n * return `Searched for: ${input.query}`;\n * });\n * ```\n */\nexport function createToolHandler<TInput = unknown, TOutput = string>(\n handler: (\n input: TInput,\n context: ToolExecutionContext\n ) => Promise<TOutput> | TOutput\n): ToolHandler<TInput, TOutput> {\n return async (input, context) => {\n return handler(input as TInput, context);\n };\n}\n\n/**\n * Build a tool handlers map from an object.\n *\n * @example\n * ```typescript\n * const handlers = buildToolHandlers({\n * search: async (input: { query: string }) => `Found: ${input.query}`,\n * calculate: async (input: { a: number, b: number }) => `${input.a + input.b}`,\n * });\n * ```\n */\nexport function buildToolHandlers(\n handlersObj: Record<string, ToolHandler>\n): Map<string, ToolHandler> {\n return new Map(Object.entries(handlersObj));\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAgB,oBACd,UACA,SACA,UAAyC,EAAE,EAC3B;AAChB,QAAO,KAAK;EACV,aAAa,SAAS,eAAe,SAAS;EAE9C,aAAa,oBAAoB,SAAS,OAAO;EAEjD,eAAe,SAAS,oBAAoB,CAAC,SAAS;EACtD,SAAS,OAAO,UAAU;GACxB,MAAM,SAAS,MAAM,QAAQ,OAAO;IAClC,SAAS,QAAQ,WAAW;IAC5B,WAAW,QAAQ,aAAa;IAChC,UAAU,QAAQ;IAClB,SAAS,QAAQ;IACjB,UAAU,QAAQ;IAClB,QAAQ,QAAQ;IACjB,CAAC;AACF,UAAO,OAAO,WAAW,WAAW,SAAS,KAAK,UAAU,OAAO;;EAEtE,CAAC;;;;;;;;;;AAWJ,SAAgB,sBACd,WACA,UACA,UAAyC,EAAE,EACX;CAChC,MAAMA,QAAwC,EAAE;AAEhD,MAAK,MAAM,YAAY,WAAW;EAChC,MAAM,UAAU,SAAS,IAAI,SAAS,KAAK;AAC3C,MAAI,CAAC,QACH,OAAM,IAAI,MAAM,6BAA6B,SAAS,OAAO;AAG/D,QAAM,SAAS,QAAQ,oBAAoB,UAAU,SAAS,QAAQ;;AAGxE,QAAO;;;;;;;;;;;;AAaT,SAAgB,kBACd,SAI8B;AAC9B,QAAO,OAAO,OAAO,YAAY;AAC/B,SAAO,QAAQ,OAAiB,QAAQ;;;;;;;;;;;;;;AAe5C,SAAgB,kBACd,aAC0B;AAC1B,QAAO,IAAI,IAAI,OAAO,QAAQ,YAAY,CAAC"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { LanguageModelUsage, ModelMessage, StepResult, ToolSet } from "ai";
|
|
2
|
+
|
|
3
|
+
//#region src/types.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Simplified tool call type for ContractSpec usage.
|
|
7
|
+
* Compatible with AI SDK v6 TypedToolCall.
|
|
8
|
+
*/
|
|
9
|
+
interface ToolCallInfo {
|
|
10
|
+
type: 'tool-call';
|
|
11
|
+
toolCallId: string;
|
|
12
|
+
toolName: string;
|
|
13
|
+
args: unknown;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Simplified tool result type for ContractSpec usage.
|
|
17
|
+
* Compatible with AI SDK v6 TypedToolResult.
|
|
18
|
+
*/
|
|
19
|
+
interface ToolResultInfo {
|
|
20
|
+
type: 'tool-result';
|
|
21
|
+
toolCallId: string;
|
|
22
|
+
toolName: string;
|
|
23
|
+
output: unknown;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Extended message type that adds metadata support to ModelMessage.
|
|
27
|
+
* Used for session memory tracking.
|
|
28
|
+
*/
|
|
29
|
+
interface AgentMessage {
|
|
30
|
+
role: 'user' | 'assistant' | 'system' | 'tool';
|
|
31
|
+
content: string | {
|
|
32
|
+
type: string;
|
|
33
|
+
text?: string;
|
|
34
|
+
[key: string]: unknown;
|
|
35
|
+
}[];
|
|
36
|
+
metadata?: Record<string, string>;
|
|
37
|
+
}
|
|
38
|
+
type AgentStatus = 'idle' | 'running' | 'waiting' | 'completed' | 'failed' | 'escalated';
|
|
39
|
+
type AgentEventName = 'agent.session.created' | 'agent.session.updated' | 'agent.step.started' | 'agent.step.completed' | 'agent.tool.called' | 'agent.tool.completed' | 'agent.tool.failed' | 'agent.tool.approval_requested' | 'agent.escalated' | 'agent.completed' | 'agent.failed';
|
|
40
|
+
type AgentFinishReason = 'stop' | 'tool-calls' | 'length' | 'content-filter' | 'error' | 'other' | 'unknown';
|
|
41
|
+
interface AgentEventPayload {
|
|
42
|
+
sessionId: string;
|
|
43
|
+
agentId: string;
|
|
44
|
+
tenantId?: string;
|
|
45
|
+
stepIndex?: number;
|
|
46
|
+
toolName?: string;
|
|
47
|
+
metadata?: Record<string, unknown>;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Runtime context passed to agent calls via AI SDK v6 callOptionsSchema.
|
|
51
|
+
* Maps to ContractSpec's tenant/actor system.
|
|
52
|
+
*/
|
|
53
|
+
interface AgentCallOptions {
|
|
54
|
+
/** Tenant scoping for guardrails and data isolation */
|
|
55
|
+
tenantId?: string;
|
|
56
|
+
/** Unique end-user identifier (for personalization) */
|
|
57
|
+
actorId?: string;
|
|
58
|
+
/** Session to resume; new session created when omitted */
|
|
59
|
+
sessionId?: string;
|
|
60
|
+
/** Arbitrary metadata forwarded to events and tool handlers */
|
|
61
|
+
metadata?: Record<string, string>;
|
|
62
|
+
}
|
|
63
|
+
interface AgentSessionState {
|
|
64
|
+
sessionId: string;
|
|
65
|
+
agentId: string;
|
|
66
|
+
tenantId?: string;
|
|
67
|
+
actorId?: string;
|
|
68
|
+
status: AgentStatus;
|
|
69
|
+
messages: ModelMessage[];
|
|
70
|
+
steps: StepResult<ToolSet>[];
|
|
71
|
+
createdAt: Date;
|
|
72
|
+
updatedAt: Date;
|
|
73
|
+
metadata?: Record<string, string>;
|
|
74
|
+
}
|
|
75
|
+
interface AgentGenerateParams {
|
|
76
|
+
/** User prompt or message */
|
|
77
|
+
prompt: string;
|
|
78
|
+
/** System prompt override (appended to agent instructions) */
|
|
79
|
+
systemOverride?: string;
|
|
80
|
+
/** Runtime context options */
|
|
81
|
+
options?: AgentCallOptions;
|
|
82
|
+
/** Maximum number of steps/iterations */
|
|
83
|
+
maxSteps?: number;
|
|
84
|
+
/** Abort signal for cancellation */
|
|
85
|
+
signal?: AbortSignal;
|
|
86
|
+
}
|
|
87
|
+
interface AgentStreamParams extends AgentGenerateParams {
|
|
88
|
+
/** Called when a step completes */
|
|
89
|
+
onStepFinish?: (step: StepResult<ToolSet>) => void | Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
interface AgentGenerateResult<TOutput = string> {
|
|
92
|
+
/** The final text response */
|
|
93
|
+
text: string;
|
|
94
|
+
/** Structured output if configured */
|
|
95
|
+
output?: TOutput;
|
|
96
|
+
/** All steps taken during generation */
|
|
97
|
+
steps: StepResult<ToolSet>[];
|
|
98
|
+
/** All tool calls made during generation */
|
|
99
|
+
toolCalls: ToolCallInfo[];
|
|
100
|
+
/** All tool results */
|
|
101
|
+
toolResults: ToolResultInfo[];
|
|
102
|
+
/** Reason generation finished */
|
|
103
|
+
finishReason: AgentFinishReason;
|
|
104
|
+
/** Token usage statistics */
|
|
105
|
+
usage?: LanguageModelUsage;
|
|
106
|
+
/** Updated session state */
|
|
107
|
+
session?: AgentSessionState;
|
|
108
|
+
/** Whether approval is pending for a tool call */
|
|
109
|
+
pendingApproval?: {
|
|
110
|
+
toolName: string;
|
|
111
|
+
toolCallId: string;
|
|
112
|
+
args: unknown;
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Context provided to tool handlers during execution.
|
|
117
|
+
*/
|
|
118
|
+
interface ToolExecutionContext {
|
|
119
|
+
agentId: string;
|
|
120
|
+
sessionId: string;
|
|
121
|
+
tenantId?: string;
|
|
122
|
+
actorId?: string;
|
|
123
|
+
metadata?: Record<string, string>;
|
|
124
|
+
signal?: AbortSignal;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Handler function for a tool.
|
|
128
|
+
*/
|
|
129
|
+
type ToolHandler<TInput = unknown, TOutput = string> = (input: TInput, context: ToolExecutionContext) => Promise<TOutput>;
|
|
130
|
+
interface AgentStepMetrics {
|
|
131
|
+
agentId: string;
|
|
132
|
+
stepIndex: number;
|
|
133
|
+
toolCalls: {
|
|
134
|
+
toolName: string;
|
|
135
|
+
durationMs?: number;
|
|
136
|
+
success: boolean;
|
|
137
|
+
error?: string;
|
|
138
|
+
}[];
|
|
139
|
+
finishReason: string;
|
|
140
|
+
usage?: LanguageModelUsage;
|
|
141
|
+
timestamp: Date;
|
|
142
|
+
}
|
|
143
|
+
type AgentEventEmitter = (event: AgentEventName, payload: AgentEventPayload) => void | Promise<void>;
|
|
144
|
+
//#endregion
|
|
145
|
+
export { AgentCallOptions, AgentEventEmitter, AgentEventName, AgentEventPayload, AgentFinishReason, AgentGenerateParams, AgentGenerateResult, AgentMessage, AgentSessionState, AgentStatus, AgentStepMetrics, AgentStreamParams, ToolCallInfo, ToolExecutionContext, ToolHandler, ToolResultInfo };
|
|
146
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;AAUA;AAWA;AAeiB,UA1BA,YAAA,CA6BJ;EAOD,IAAA,EAAA,WAAW;EAQX,UAAA,EAAA,MAAc;EAad,QAAA,EAAA,MAAA;EASK,IAAA,EAAA,OAAA;AAiBjB;AAeA;;;;AAOS,UA9FQ,cAAA,CA8FR;EACI,IAAA,EAAA,aAAA;EACA,UAAA,EAAA,MAAA;EACA,QAAA,EAAA,MAAA;EAAM,MAAA,EAAA,OAAA;AAOnB;AAaA;;;;AAA2C,UAtG1B,YAAA,CAsG0B;EAAmB,IAAA,EAAA,MAAA,GAAA,WAAA,GAAA,QAAA,GAAA,MAAA;EAS7C,OAAA,EAAA,MAAA,GAAA;IAIN,IAAA,EAAA,MAAA;IAES,IAAA,CAAA,EAAA,MAAA;IAAX,CAAA,GAAA,EAAA,MAAA,CAAA,EAAA,OAAA;EAEI,CAAA,EAAA;EAEE,QAAA,CAAA,EAtHF,MAsHE,CAAA,MAAA,EAAA,MAAA,CAAA;;AAIL,KAnHE,WAAA,GAmHF,MAAA,GAAA,SAAA,GAAA,SAAA,GAAA,WAAA,GAAA,QAAA,GAAA,WAAA;AAEE,KA7GA,cAAA,GA6GA,uBAAA,GAAA,uBAAA,GAAA,oBAAA,GAAA,sBAAA,GAAA,mBAAA,GAAA,sBAAA,GAAA,mBAAA,GAAA,+BAAA,GAAA,iBAAA,GAAA,iBAAA,GAAA,cAAA;AAAiB,KAhGjB,iBAAA,GAgGiB,MAAA,GAAA,YAAA,GAAA,QAAA,GAAA,gBAAA,GAAA,OAAA,GAAA,OAAA,GAAA,SAAA;AAgBZ,UAvGA,iBAAA,CAuGoB;EAYzB,SAAA,EAAA,MAAW;EACd,OAAA,EAAA,MAAA;EACE,QAAA,CAAA,EAAA,MAAA;EACE,SAAA,CAAA,EAAA,MAAA;EAAR,QAAA,CAAA,EAAA,MAAA;EAAO,QAAA,CAAA,EAhHC,MAgHD,CAAA,MAAA,EAAA,OAAA,CAAA;AAMZ;AAkBA;;;;AAGmB,UAhIF,gBAAA,CAgIE;;;;;;;;aAxHN;;UAOI,iBAAA;;;;;UAKP;YACE;SACH,WAAW;aACP;aACA;aACA;;UAOI,mBAAA;;;;;;YAML;;;;WAID;;UAGM,iBAAA,SAA0B;;wBAEnB,WAAW,oBAAoB;;UAOtC;;;;WAIN;;SAEF,WAAW;;aAEP;;eAEE;;gBAEC;;UAEN;;YAEE;;;;;;;;;;;UAgBK,oBAAA;;;;;aAKJ;WACF;;;;;KAMC,0DACH,iBACE,yBACN,QAAQ;UAMI,gBAAA;;;;;;;;;;UAUP;aACG;;KAOD,iBAAA,WACH,yBACE,6BACC"}
|
package/dist/types.js
ADDED
|
File without changes
|