1+ import { MCPClientManager } from "agents/mcp/client"
2+ import { LanguageModelV1 , StepResult , ToolSet , generateText , streamText , tool } from "ai"
3+ import { jsonSchemaToZod , type JsonSchemaObject } from "@n8n/json-schema-to-zod" ;
4+
5+ export async function runTask ( model : LanguageModelV1 , input : string ) {
6+ const clientManager = new MCPClientManager ( "test-client" , "0.0.0" )
7+ await clientManager . connect ( "http://localhost:8787/sse" )
8+
9+ const tools = clientManager . listTools ( )
10+ const toolSet : ToolSet = tools . reduce ( ( acc , v ) => {
11+ acc [ v . name ] = tool ( {
12+ parameters : jsonSchemaToZod ( v . inputSchema as JsonSchemaObject ) ,
13+ description : v . description ,
14+ execute : async ( args , opts ) => {
15+ console . log ( `executing tool ${ v . name } ` )
16+ const res = await clientManager . callTool ( v , args , { signal : opts . abortSignal } )
17+ console . log ( res . toolResult )
18+ return res . content
19+ } ,
20+ } )
21+ return acc
22+ } , { } as ToolSet )
23+
24+ const res = streamText ( {
25+ model,
26+ system : "You are an assistant responsible for evaluating the results of calling various tools. Given the user's query, use the tools available to you to answer the question." ,
27+ tools : toolSet ,
28+ prompt : input ,
29+ maxRetries : 1 ,
30+ maxSteps : 10 ,
31+ } )
32+
33+ for await ( const part of res . fullStream ) {
34+
35+ }
36+
37+ let messagesWithTools = ""
38+ const messages = ( await res . response ) . messages
39+ for ( const message of messages ) {
40+ console . log ( message . content )
41+ for ( const messagePart of message . content ) {
42+ if ( typeof messagePart === "string" ) {
43+ messagesWithTools += `<message_content type="text">
44+ ${ messagePart }
45+ </message_content>`
46+ } else if ( messagePart . type === "tool-call" ) {
47+ messagesWithTools += `<message_content type=${ messagePart . type } >
48+ <tool_name>${ messagePart . toolName } </tool_name>
49+ <tool_arguments>${ JSON . stringify ( messagePart . args ) } </tool_arguments>
50+ </message_content>`
51+ } else if ( messagePart . type === "text" ) {
52+ messagesWithTools += `<message_content type="text">
53+ ${ messagePart . text }
54+ </message_content>`
55+ }
56+ }
57+ }
58+
59+ console . log ( messagesWithTools )
60+
61+ return messagesWithTools
62+ }
0 commit comments