File size: 6,331 Bytes
bfc7d04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// MCP Client - Model Context Protocol client for Stack 2.9
//
// Provides MCP server integration for tool extensibility.
// Supports stdio, SSE, and HTTP transports.

export type MCPTransportType = 'stdio' | 'sse' | 'http'

export interface MCPConfig {
  name: string
  command?: string
  args?: string[]
  env?: Record<string, string>
  url?: string
  transport?: MCPTransportType
}

export interface MCPTool {
  name: string
  description: string
  inputSchema: Record<string, unknown>
}

export interface MCPResource {
  uri: string
  name: string
  description?: string
  mimeType?: string
}

export interface MCP_SERVER_CONFIG {
  name: string
  transport: 'stdio' | 'sse' | 'http'
  command?: string
  args?: string[]
  env?: Record<string, string>
  url?: string
}

interface MCPRequest {
  jsonrpc: '2.0'
  id: number | string
  method: string
  params?: Record<string, unknown>
}

interface MCPResponse {
  jsonrpc: '2.0'
  id: number | string
  result?: unknown
  error?: {
    code: number
    message: string
    data?: unknown
  }
}

// ─── MCP Client ───

export class MCPClient {
  private config: MCP_SERVER_CONFIG
  private requestId = 0
  private pendingRequests: Map<number | string, {
    resolve: (value: unknown) => void
    reject: (error: Error) => void
  }> = new Map()

  constructor(config: MCP_SERVER_CONFIG) {
    this.config = config
  }

  get name(): string {
    return this.config.name
  }

  get transport(): string {
    return this.config.transport
  }

  // Send an MCP request and wait for response
  async sendRequest(method: string, params?: Record<string, unknown>): Promise<unknown> {
    const id = ++this.requestId
    const request: MCPRequest = {
      jsonrpc: '2.0',
      id,
      method,
      params,
    }

    return new Promise((resolve, reject) => {
      this.pendingRequests.set(id, { resolve, reject })

      if (this.config.transport === 'stdio') {
        this.sendStdioRequest(request)
      } else if (this.config.transport === 'http' || this.config.transport === 'sse') {
        this.sendHttpRequest(request)
      }
    })
  }

  private async sendStdioRequest(request: MCPRequest): Promise<void> {
    // In stdio mode, would spawn the process and communicate via stdin/stdout
    console.log('[mcp] Stdio request:', request)
  }

  private async sendHttpRequest(request: MCPRequest): Promise<void> {
    const url = this.config.url
    if (!url) {
      throw new Error('MCP HTTP client requires URL')
    }

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(request),
      })

      if (!response.ok) {
        throw new Error(`MCP request failed: ${response.status}`)
      }

      const data = await response.json() as MCPResponse
      const pending = this.pendingRequests.get(data.id)
      if (pending) {
        if (data.error) {
          pending.reject(new Error(data.error.message))
        } else {
          pending.resolve(data.result)
        }
        this.pendingRequests.delete(data.id)
      }
    } catch (error) {
      // Reject all pending requests
      for (const [, pending] of this.pendingRequests) {
        pending.reject(error as Error)
      }
      this.pendingRequests.clear()
    }
  }

  // List available tools
  async listTools(): Promise<MCPTool[]> {
    try {
      const result = await this.sendRequest('tools/list') as {
        tools: Array<{
          name: string
          description?: string
          inputSchema?: Record<string, unknown>
        }>
      }
      return (result.tools ?? []).map(t => ({
        name: t.name,
        description: t.description ?? '',
        inputSchema: t.inputSchema ?? {},
      }))
    } catch {
      return []
    }
  }

  // Call a tool
  async callTool(name: string, args: Record<string, unknown>): Promise<unknown> {
    return this.sendRequest('tools/call', { name, arguments: args })
  }

  // List available resources
  async listResources(): Promise<MCPResource[]> {
    try {
      const result = await this.sendRequest('resources/list') as {
        resources: Array<{
          uri: string
          name: string
          description?: string
          mimeType?: string
        }>
      }
      return (result.resources ?? []).map(r => ({
        uri: r.uri,
        name: r.name,
        description: r.description,
        mimeType: r.mimeType,
      }))
    } catch {
      return []
    }
  }

  // Read a resource
  async readResource(uri: string): Promise<unknown> {
    return this.sendRequest('resources/read', { uri })
  }
}

// ─── MCP Connection Manager ───

export class MCPConnectionManager {
  private connections: Map<string, MCPClient> = new Map()

  async addServer(config: MCP_SERVER_CONFIG): Promise<MCPClient> {
    const client = new MCPClient(config)
    this.connections.set(config.name, client)

    // Initialize the connection
    try {
      await client.sendRequest('initialize', {
        protocolVersion: '2024-11-05',
        capabilities: {},
        clientInfo: {
          name: 'stack-2.9',
          version: '1.0.0',
        },
      })
      console.log(`[mcp] Connected to ${config.name}`)
    } catch (error) {
      console.error(`[mcp] Failed to connect to ${config.name}:`, error)
    }

    return client
  }

  getServer(name: string): MCPClient | undefined {
    return this.connections.get(name)
  }

  removeServer(name: string): void {
    this.connections.delete(name)
  }

  listServers(): string[] {
    return Array.from(this.connections.keys())
  }

  async closeAll(): Promise<void> {
    for (const [name, client] of this.connections) {
      try {
        await client.sendRequest('shutdown')
      } catch {
        // Ignore shutdown errors
      }
      console.log(`[mcp] Disconnected from ${name}`)
    }
    this.connections.clear()
  }
}

// ─── Factory ───

export function createMCPClient(config: MCPConfig): MCPClient {
  const serverConfig: MCP_SERVER_CONFIG = {
    name: config.name,
    transport: config.transport ?? 'stdio',
    command: config.command,
    args: config.args,
    env: config.env,
    url: config.url,
  }

  return new MCPClient(serverConfig)
}

export default {
  MCPClient,
  MCPConnectionManager,
  createMCPClient,
}