@@ -3,32 +3,49 @@ import {
3
3
ClientOptions ,
4
4
} from "@modelcontextprotocol/sdk/client/index.js" ;
5
5
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js" ;
6
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js" ;
6
7
import { MCPConnectionError } from "../../types/stagehandErrors" ;
7
8
8
9
export interface ConnectToMCPServerOptions {
9
10
serverUrl : string | URL ;
10
11
clientOptions ?: ClientOptions ;
11
12
}
12
13
14
+ export interface StdioServerConfig {
15
+ command : string ;
16
+ args ?: string [ ] ;
17
+ env ?: Record < string , string > ;
18
+ }
19
+
13
20
export const connectToMCPServer = async (
14
- serverUrlOrOptions : string | ConnectToMCPServerOptions ,
21
+ serverConfig : string | URL | StdioServerConfig | ConnectToMCPServerOptions ,
15
22
) : Promise < Client > => {
16
- // Handle both string URL and options object
17
- const options : ConnectToMCPServerOptions =
18
- typeof serverUrlOrOptions === "string"
19
- ? { serverUrl : serverUrlOrOptions }
20
- : serverUrlOrOptions ;
23
+ try {
24
+ let transport ;
25
+ let clientOptions : ClientOptions | undefined ;
21
26
22
- const serverUrl = options . serverUrl . toString ( ) ;
27
+ // Check if it's a stdio config (has 'command' property)
28
+ if ( typeof serverConfig === "object" && "command" in serverConfig ) {
29
+ transport = new StdioClientTransport ( serverConfig ) ;
30
+ } else {
31
+ // Handle URL-based connection
32
+ let serverUrl : string | URL ;
33
+
34
+ if ( typeof serverConfig === "string" || serverConfig instanceof URL ) {
35
+ serverUrl = serverConfig ;
36
+ } else {
37
+ serverUrl = ( serverConfig as ConnectToMCPServerOptions ) . serverUrl ;
38
+ clientOptions = ( serverConfig as ConnectToMCPServerOptions )
39
+ . clientOptions ;
40
+ }
41
+
42
+ transport = new StreamableHTTPClientTransport ( new URL ( serverUrl ) ) ;
43
+ }
23
44
24
- try {
25
- const transport = new StreamableHTTPClientTransport (
26
- new URL ( options . serverUrl ) ,
27
- ) ;
28
45
const client = new Client ( {
29
46
name : "Stagehand" ,
30
47
version : "1.0.0" ,
31
- ...options . clientOptions ,
48
+ ...clientOptions ,
32
49
} ) ;
33
50
34
51
await client . connect ( transport ) ;
@@ -37,7 +54,7 @@ export const connectToMCPServer = async (
37
54
await client . ping ( ) ;
38
55
} catch ( pingError ) {
39
56
await client . close ( ) ;
40
- throw new MCPConnectionError ( serverUrl , pingError ) ;
57
+ throw new MCPConnectionError ( serverConfig . toString ( ) , pingError ) ;
41
58
}
42
59
43
60
return client ;
@@ -46,6 +63,6 @@ export const connectToMCPServer = async (
46
63
if ( error instanceof MCPConnectionError ) {
47
64
throw error ; // Re-throw our custom error
48
65
}
49
- throw new MCPConnectionError ( serverUrl , error ) ;
66
+ throw new MCPConnectionError ( serverConfig . toString ( ) , error ) ;
50
67
}
51
68
} ;
0 commit comments