This repository was archived by the owner on May 21, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathserver_manager.ts
More file actions
188 lines (158 loc) · 6.52 KB
/
Copy pathserver_manager.ts
File metadata and controls
188 lines (158 loc) · 6.52 KB
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
import type { StructuredToolInterface } from '@langchain/core/tools'
import type { LangChainAdapter } from '../adapters/langchain_adapter.js'
import type { MCPClient } from '../client.js'
import type { BaseConnector } from '../connectors/base.js'
import { DynamicStructuredTool } from '@langchain/core/tools'
import { z } from 'zod'
import { logger } from '../logging.js'
const ServerActionInputSchema = z.object({
serverName: z.string().describe('The name of the MCP server'),
})
const DisconnectServerInputSchema = z.object({})
const ListServersInputSchema = z.object({})
const CurrentServerInputSchema = z.object({})
export class ServerManager {
private activeServer: string | null = null
private readonly initializedServers: Record<string, boolean> = {}
private readonly serverTools: Record<string, StructuredToolInterface[]> = {}
constructor(
private readonly client: MCPClient,
private readonly adapter: LangChainAdapter,
) {}
async initialize(): Promise<void> {
if (!this.client.getServerNames?.().length) {
logger.warning('No MCP servers defined in client configuration')
}
}
async getServerManagementTools(): Promise<StructuredToolInterface[]> {
const listServersTool = new DynamicStructuredTool({
name: 'list_mcp_servers',
description:
'Lists all available MCP (Model Context Protocol) servers that can be connected to, along with the tools available on each server. Use this tool to discover servers and see what functionalities they offer.',
schema: ListServersInputSchema,
func: async () => this.listServers(),
})
const connectServerTool = new DynamicStructuredTool({
name: 'connect_to_mcp_server',
description: 'Connect to a specific MCP (Model Context Protocol) server to use its tools. Use this tool to connect to a specific server and use its tools.',
schema: ServerActionInputSchema,
func: async ({ serverName }) => this.connectToServer(serverName),
})
const getActiveServerTool = new DynamicStructuredTool({
name: 'get_active_mcp_server',
description: 'Get the currently active MCP (Model Context Protocol) server.',
schema: CurrentServerInputSchema,
func: async () => this.getActiveServer(),
})
const disconnectServerTool = new DynamicStructuredTool({
name: 'disconnect_from_mcp_server',
description: 'Disconnect from the currently active MCP (Model Context Protocol) server.',
schema: DisconnectServerInputSchema,
func: async () => this.disconnectFromServer(),
})
return [
listServersTool,
connectServerTool,
getActiveServerTool,
disconnectServerTool,
]
}
async listServers(): Promise<string> {
const servers = this.client.getServerNames?.() ?? []
if (!servers.length)
return 'No MCP servers are currently defined.'
let out = 'Available MCP servers:\n'
for (const [idx, serverName] of servers.entries()) {
const active = serverName === this.activeServer ? ' (ACTIVE)' : ''
out += `${idx + 1}. ${serverName}${active}\n`
try {
const tools = await this.ensureToolsFetched(serverName)
out += tools.length
? ` Tools: ${tools.map(t => t.name).join(', ')}\n`
: ' Tools: (Could not retrieve or none available)\n'
}
catch (err) {
logger?.error?.(`Error listing tools for server '${serverName}':`, err)
out += ' Tools: (Error retrieving tools)\n'
}
}
return out
}
async connectToServer(serverName: string): Promise<string> {
const servers = this.client.getServerNames() ?? []
if (!servers.includes(serverName)) {
return `Server '${serverName}' not found. Available servers: ${servers.join(', ') || 'none'}`
}
if (this.activeServer === serverName) {
return `Already connected to MCP server '${serverName}'`
}
try {
const session = await this.ensureSession(serverName, /* create */ true)
this.activeServer = serverName
// Ensure tools cached
await this.ensureToolsFetched(serverName, session?.connector)
const tools = this.serverTools[serverName] ?? []
const toolDetails = tools
.map((t, i) => `${i + 1}. ${t.name}: ${t.description}`)
.join('\n')
return (
`Connected to MCP server '${serverName}'. ${tools.length} tools are now available.${
tools.length ? `\nAvailable tools for this server:\n${toolDetails}` : ''}`
)
}
catch (err) {
logger.error(`Error connecting to server '${serverName}':`, err)
return `Failed to connect to server '${serverName}': ${String(err)}`
}
}
async getActiveServer(): Promise<string> {
return this.activeServer
? `Currently active MCP server: ${this.activeServer}`
: 'No MCP server is currently active. Use connect_to_mcp_server to connect.'
}
async disconnectFromServer(): Promise<string> {
if (!this.activeServer) {
return 'No MCP server is currently active, so there\'s nothing to disconnect from.'
}
const was = this.activeServer
this.activeServer = null
return `Successfully disconnected from MCP server '${was}'.`
}
async getActiveServerTools(): Promise<StructuredToolInterface[]> {
return this.activeServer ? this.serverTools[this.activeServer] ?? [] : []
}
async getAllTools(): Promise<StructuredToolInterface[]> {
return [...(await this.getServerManagementTools()), ...(await this.getActiveServerTools())]
}
private async ensureSession(serverName: string, createIfMissing = false) {
try {
return this.client.getSession(serverName)
}
catch {
if (!createIfMissing)
return undefined
return this.client.createSession ? await this.client.createSession(serverName) : undefined
}
}
private async ensureToolsFetched(serverName: string, connector?: BaseConnector): Promise<StructuredToolInterface[]> {
if (this.serverTools[serverName])
return this.serverTools[serverName]
const session = connector ? { connector } : await this.ensureSession(serverName, true)
if (!session) {
this.serverTools[serverName] = []
return []
}
try {
const tools = await this.adapter.createToolsFromConnectors([session.connector])
this.serverTools[serverName] = tools
this.initializedServers[serverName] = true
logger.debug(`Fetched ${tools.length} tools for server '${serverName}'.`)
return tools
}
catch (err) {
logger.warning(`Could not fetch tools for server '${serverName}':`, err)
this.serverTools[serverName] = []
return []
}
}
}