@@ -2,8 +2,22 @@ import { experimental_createMCPClient, type Tool } from "ai"
22import { Experimental_StdioMCPTransport } from "ai/mcp-stdio"
33import { App } from "../app/app"
44import { Config } from "../config/config"
5+ import { Log } from "../util/log"
6+ import { NamedError } from "../util/error"
7+ import { z } from "zod"
8+ import { Session } from "../session"
9+ import { Bus } from "../bus"
510
611export namespace MCP {
12+ const log = Log . create ( { service : "mcp" } )
13+
14+ export const Failed = NamedError . create (
15+ "MCPFailed" ,
16+ z . object ( {
17+ name : z . string ( ) ,
18+ } ) ,
19+ )
20+
721 const state = App . state (
822 "mcp" ,
923 async ( ) => {
@@ -12,27 +26,56 @@ export namespace MCP {
1226 [ name : string ] : Awaited < ReturnType < typeof experimental_createMCPClient > >
1327 } = { }
1428 for ( const [ key , mcp ] of Object . entries ( cfg . mcp ?? { } ) ) {
29+ log . info ( "found" , { key, type : mcp . type } )
1530 if ( mcp . type === "remote" ) {
16- clients [ key ] = await experimental_createMCPClient ( {
31+ const client = await experimental_createMCPClient ( {
1732 name : key ,
1833 transport : {
1934 type : "sse" ,
2035 url : mcp . url ,
2136 } ,
22- } )
37+ } ) . catch ( ( ) => { } )
38+ if ( ! client ) {
39+ Bus . publish ( Session . Event . Error , {
40+ error : {
41+ name : "UnknownError" ,
42+ data : {
43+ message : `MCP server ${ key } failed to start` ,
44+ } ,
45+ } ,
46+ } )
47+ continue
48+ }
49+ clients [ key ] = client
2350 }
2451
2552 if ( mcp . type === "local" ) {
2653 const [ cmd , ...args ] = mcp . command
27- clients [ key ] = await experimental_createMCPClient ( {
54+ const client = await experimental_createMCPClient ( {
2855 name : key ,
2956 transport : new Experimental_StdioMCPTransport ( {
3057 stderr : "ignore" ,
3158 command : cmd ,
3259 args,
33- env : mcp . environment ,
60+ env : {
61+ ...process . env ,
62+ ...( cmd === "opencode" ? { BUN_BE_BUN : "1" } : { } ) ,
63+ ...mcp . environment ,
64+ } ,
3465 } ) ,
35- } )
66+ } ) . catch ( ( ) => { } )
67+ if ( ! client ) {
68+ Bus . publish ( Session . Event . Error , {
69+ error : {
70+ name : "UnknownError" ,
71+ data : {
72+ message : `MCP server ${ key } failed to start` ,
73+ } ,
74+ } ,
75+ } )
76+ continue
77+ }
78+ clients [ key ] = client
3679 }
3780 }
3881
0 commit comments