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
130 lines (110 loc) · 4.55 KB
/
Copy pathserver_manager.ts
File metadata and controls
130 lines (110 loc) · 4.55 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
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 type { MCPSession } from '../session.js'
import { isEqual } from 'lodash-es'
import { logger } from '../logging.js'
import { AcquireActiveMCPServerTool } from './tools/acquire_active_mcp_server.js'
import { AddMCPServerTool } from './tools/add_server.js'
import { ConnectMCPServerTool } from './tools/connect_mcp_server.js'
import { ListMCPServersTool } from './tools/list_mcp_servers.js'
import { ReleaseMCPServerConnectionTool } from './tools/release_mcp_server_connection.js'
export class ServerManager {
public readonly initializedServers: Record<string, boolean> = {}
public readonly serverTools: Record<string, StructuredToolInterface[]> = {}
public readonly client: MCPClient
public readonly adapter: LangChainAdapter
public activeServer: string | null = null
constructor(client: MCPClient, adapter: LangChainAdapter) {
this.client = client
this.adapter = adapter
}
public logState(context: string): void {
const allServerNames = this.client.getServerNames()
const activeSessionNames = Object.keys(this.client.getAllActiveSessions())
if (allServerNames.length === 0) {
logger.info('Server Manager State: No servers configured.')
return
}
const tableData = allServerNames.map(name => ({
'Server Name': name,
'Connected': activeSessionNames.includes(name) ? '✅' : '❌',
'Initialized': this.initializedServers[name] ? '✅' : '❌',
'Tool Count': this.serverTools[name]?.length ?? 0,
'Active': this.activeServer === name ? '✅' : '❌',
}))
logger.info(`Server Manager State: [${context}]`)
console.table(tableData) // eslint-disable-line no-console
}
initialize(): void {
const serverNames = this.client.getServerNames?.()
if (serverNames.length === 0) {
logger.warn('No MCP servers defined in client configuration')
}
}
async prefetchServerTools(): Promise<void> {
const servers: string[] = this.client.getServerNames()
for (const serverName of servers) {
try {
let session: MCPSession | null = null
session = this.client.getSession(serverName)
logger.debug(`Using existing session for server '${serverName}' to prefetch tools.`)
if (!session) {
session = await this.client.createSession(serverName).catch((createSessionError) => {
logger.warn(`Could not create session for '${serverName}' during prefetch: ${createSessionError}`)
return null
})
logger.debug(`Temporarily created session for '${serverName}' to prefetch tools.`)
}
if (session) {
const connector: BaseConnector = session.connector
let tools: StructuredToolInterface[] = []
try {
tools = await this.adapter.createToolsFromConnectors([connector])
}
catch (toolFetchError) {
logger.error(`Failed to create tools from connector for server '${serverName}': ${toolFetchError}`)
continue
}
const cachedTools = this.serverTools[serverName]
const toolsChanged
= !cachedTools || !isEqual(cachedTools, tools)
if (toolsChanged) {
this.serverTools[serverName] = tools
this.initializedServers[serverName] = true
logger.debug(`Prefetched ${tools.length} tools for server '${serverName}'.`)
}
else {
logger.debug(
`Tools for server '${serverName}' unchanged, using cached version.`,
)
}
}
}
catch (outerError) {
logger.error(`Error prefetching tools for server '${serverName}': ${outerError}`)
}
}
}
get tools(): StructuredToolInterface[] {
if (logger.level === 'debug') {
this.logState('Providing tools to agent')
}
const managementTools = [
new AddMCPServerTool(this),
new ListMCPServersTool(this),
new ConnectMCPServerTool(this),
new AcquireActiveMCPServerTool(this),
new ReleaseMCPServerConnectionTool(this),
]
if (this.activeServer && this.serverTools[this.activeServer]) {
const activeTools = this.serverTools[this.activeServer]
logger.debug(
`Adding ${activeTools.length} tools from active server '${this.activeServer}'`,
)
return [...managementTools, ...activeTools]
}
return managementTools
}
}