-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathindex.ts
More file actions
1103 lines (984 loc) · 35.6 KB
/
index.ts
File metadata and controls
1103 lines (984 loc) · 35.6 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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { dynamicTool, type Tool, jsonSchema, type JSONSchema7 } from "ai"
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
import {
CallToolResultSchema,
type Tool as MCPToolDef,
ToolListChangedNotificationSchema,
} from "@modelcontextprotocol/sdk/types.js"
import { Config } from "../config/config"
import { Log } from "../util/log"
import { NamedError } from "@opencode-ai/util/error"
import z from "zod/v4"
import { Instance } from "../project/instance"
import { Installation } from "../installation"
import { withTimeout } from "@/util/timeout"
import { McpOAuthProvider } from "./oauth-provider"
import { McpOAuthCallback } from "./oauth-callback"
import { McpAuth } from "./auth"
import { BusEvent } from "../bus/bus-event"
import { Bus } from "@/bus"
import { TuiEvent } from "@/cli/cmd/tui/event"
import open from "open"
import { Telemetry } from "@/telemetry"
export namespace MCP {
const log = Log.create({ service: "mcp" })
const DEFAULT_TIMEOUT = 30_000
const registeredMcpTools = new Set<string>()
export function isMcpTool(name: string): boolean {
return registeredMcpTools.has(name)
}
export const Resource = z
.object({
name: z.string(),
uri: z.string(),
description: z.string().optional(),
mimeType: z.string().optional(),
client: z.string(),
})
.meta({ ref: "McpResource" })
export type Resource = z.infer<typeof Resource>
export const ToolsChanged = BusEvent.define(
"mcp.tools.changed",
z.object({
server: z.string(),
}),
)
export const BrowserOpenFailed = BusEvent.define(
"mcp.browser.open.failed",
z.object({
mcpName: z.string(),
url: z.string(),
}),
)
export const Failed = NamedError.create(
"MCPFailed",
z.object({
name: z.string(),
}),
)
type MCPClient = Client
export const Status = z
.discriminatedUnion("status", [
z
.object({
status: z.literal("connected"),
})
.meta({
ref: "MCPStatusConnected",
}),
z
.object({
status: z.literal("disabled"),
})
.meta({
ref: "MCPStatusDisabled",
}),
z
.object({
status: z.literal("failed"),
error: z.string(),
})
.meta({
ref: "MCPStatusFailed",
}),
z
.object({
status: z.literal("needs_auth"),
})
.meta({
ref: "MCPStatusNeedsAuth",
}),
z
.object({
status: z.literal("needs_client_registration"),
error: z.string(),
})
.meta({
ref: "MCPStatusNeedsClientRegistration",
}),
])
.meta({
ref: "MCPStatus",
})
export type Status = z.infer<typeof Status>
// Register notification handlers for MCP client
function registerNotificationHandlers(client: MCPClient, serverName: string) {
client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
log.info("tools list changed notification received", { server: serverName })
Bus.publish(ToolsChanged, { server: serverName })
})
}
// Convert MCP tool definition to AI SDK Tool type
async function convertMcpTool(mcpTool: MCPToolDef, client: MCPClient, timeout?: number): Promise<Tool> {
const inputSchema = mcpTool.inputSchema
// Spread first, then override type to ensure it's always "object"
const schema: JSONSchema7 = {
...(inputSchema as JSONSchema7),
type: "object",
properties: (inputSchema.properties ?? {}) as JSONSchema7["properties"],
additionalProperties: false,
}
return dynamicTool({
description: mcpTool.description ?? "",
inputSchema: jsonSchema(schema),
execute: async (args: unknown) => {
return client.callTool(
{
name: mcpTool.name,
arguments: (args || {}) as Record<string, unknown>,
},
CallToolResultSchema,
{
resetTimeoutOnProgress: true,
timeout,
},
)
},
})
}
// Store transports for OAuth servers to allow finishing auth
type TransportWithAuth = StreamableHTTPClientTransport | SSEClientTransport
const pendingOAuthTransports = new Map<string, TransportWithAuth>()
// Prompt cache types
type PromptInfo = Awaited<ReturnType<MCPClient["listPrompts"]>>["prompts"][number]
type ResourceInfo = Awaited<ReturnType<MCPClient["listResources"]>>["resources"][number]
type McpEntry = NonNullable<Config.Info["mcp"]>[string]
function isMcpConfigured(entry: McpEntry): entry is Config.Mcp {
return typeof entry === "object" && entry !== null && "type" in entry
}
const state = Instance.state(
async () => {
const cfg = await Config.get()
const config = cfg.mcp ?? {}
const clients: Record<string, MCPClient> = {}
const status: Record<string, Status> = {}
const transports: Record<string, "stdio" | "sse" | "streamable-http"> = {}
// altimate_change start — auto-discover MCP servers from external AI tool configs
let discoveryResult: { serverNames: string[]; sources: string[] } | null = null
try {
const { consumeDiscoveryResult } = await import("./discover")
discoveryResult = consumeDiscoveryResult()
} catch {
// Discovery module not loaded — skip
}
// altimate_change end
await Promise.all(
Object.entries(config).map(async ([key, mcp]) => {
if (!isMcpConfigured(mcp)) {
log.error("Ignoring MCP config entry without type", { key })
return
}
// If disabled by config, mark as disabled without trying to connect
if (mcp.enabled === false) {
status[key] = { status: "disabled" }
return
}
const result = await create(key, mcp).catch((e) => {
log.warn("failed to initialize MCP server", { key, error: e instanceof Error ? e.message : String(e) })
return undefined
})
if (!result) return
status[key] = result.status
if (result.mcpClient) {
clients[key] = result.mcpClient
if (result.transport) transports[key] = result.transport
}
}),
)
// altimate_change start — show discovery toast after MCP connections complete
if (discoveryResult) {
const message = `Discovered ${discoveryResult.serverNames.length} new MCP server(s): ${discoveryResult.serverNames.join(", ")}. Ask the assistant to add them, or they will be available automatically in the current session.`
Bus.publish(TuiEvent.ToastShow, {
title: "MCP Servers Discovered",
message,
variant: "info",
duration: 8000,
}).catch(() => {})
Telemetry.track({
type: "mcp_discovery",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
server_count: discoveryResult.serverNames.length,
server_names: discoveryResult.serverNames,
sources: discoveryResult.sources,
})
}
// altimate_change end
return {
status,
clients,
transports,
}
},
async (state) => {
await Promise.all(
Object.values(state.clients).map((client) =>
client.close().catch((error) => {
log.error("Failed to close MCP client", {
error,
})
}),
),
)
pendingOAuthTransports.clear()
},
)
// Helper function to fetch prompts for a specific client
async function fetchPromptsForClient(clientName: string, client: Client) {
const prompts = await withTimeout(client.listPrompts(), DEFAULT_TIMEOUT).catch((e) => {
log.error("failed to get prompts", { clientName, error: e.message })
return undefined
})
if (!prompts) {
return
}
const commands: Record<string, PromptInfo & { client: string }> = {}
for (const prompt of prompts.prompts) {
const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
const sanitizedPromptName = prompt.name.replace(/[^a-zA-Z0-9_-]/g, "_")
const key = sanitizedClientName + ":" + sanitizedPromptName
commands[key] = { ...prompt, client: clientName }
}
return commands
}
async function fetchResourcesForClient(clientName: string, client: Client) {
const resources = await withTimeout(client.listResources(), DEFAULT_TIMEOUT).catch((e) => {
log.error("failed to get resources", { clientName, error: e.message })
return undefined
})
if (!resources) {
return
}
const commands: Record<string, ResourceInfo & { client: string }> = {}
for (const resource of resources.resources) {
const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
const sanitizedResourceName = resource.name.replace(/[^a-zA-Z0-9_-]/g, "_")
const key = sanitizedClientName + ":" + sanitizedResourceName
commands[key] = { ...resource, client: clientName }
}
return commands
}
export async function add(name: string, mcp: Config.Mcp) {
const s = await state()
const result = await create(name, mcp)
if (!result) {
const status = {
status: "failed" as const,
error: "unknown error",
}
s.status[name] = status
Bus.publish(ToolsChanged, { server: name })
return {
status,
}
}
if (!result.mcpClient) {
s.status[name] = result.status
Bus.publish(ToolsChanged, { server: name })
return {
status: s.status,
}
}
// Close existing client if present to prevent memory leaks
const existingClient = s.clients[name]
if (existingClient) {
await existingClient.close().catch((error) => {
log.error("Failed to close existing MCP client", { name, error })
})
}
s.clients[name] = result.mcpClient
s.status[name] = result.status
if (result.transport) s.transports[name] = result.transport
Bus.publish(ToolsChanged, { server: name })
return {
status: s.status,
}
}
async function create(key: string, mcp: Config.Mcp) {
if (mcp.enabled === false) {
log.info("mcp server disabled", { key })
return {
mcpClient: undefined,
status: { status: "disabled" as const },
}
}
log.info("found", { key, type: mcp.type })
let mcpClient: MCPClient | undefined
let status: Status | undefined = undefined
let connectedTransport: "stdio" | "sse" | "streamable-http" | undefined = undefined
if (mcp.type === "remote") {
// OAuth is enabled by default for remote servers unless explicitly disabled with oauth: false
const oauthDisabled = mcp.oauth === false
const oauthConfig = typeof mcp.oauth === "object" ? mcp.oauth : undefined
let authProvider: McpOAuthProvider | undefined
if (!oauthDisabled) {
authProvider = new McpOAuthProvider(
key,
mcp.url,
{
clientId: oauthConfig?.clientId,
clientSecret: oauthConfig?.clientSecret,
scope: oauthConfig?.scope,
},
{
onRedirect: async (url) => {
log.info("oauth redirect requested", { key, url: url.toString() })
// Store the URL - actual browser opening is handled by startAuth
},
},
)
}
const transports: Array<{ name: string; transport: TransportWithAuth }> = [
{
name: "StreamableHTTP",
transport: new StreamableHTTPClientTransport(new URL(mcp.url), {
authProvider,
requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
}),
},
{
name: "SSE",
transport: new SSEClientTransport(new URL(mcp.url), {
authProvider,
requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
}),
},
]
let lastError: Error | undefined
const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
for (const { name, transport } of transports) {
const connectStart = Date.now()
try {
const client = new Client({
name: "altimate",
version: Installation.VERSION,
})
await withTimeout(client.connect(transport), connectTimeout)
registerNotificationHandlers(client, key)
mcpClient = client
connectedTransport = name === "SSE" ? "sse" : "streamable-http"
log.info("connected", { key, transport: name })
status = { status: "connected" }
Telemetry.track({
type: "mcp_server_status",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
server_name: key,
transport: connectedTransport,
status: "connected",
duration_ms: Date.now() - connectStart,
})
// Census: collect tool and resource counts (fire-and-forget, never block connect)
const remoteTransport = name === "SSE" ? "sse" as const : "streamable-http" as const
void Promise.all([
client.listTools().catch(() => ({ tools: [] })),
client.listResources().catch(() => ({ resources: [] })),
]).then(([toolsList, resourcesList]) => {
Telemetry.track({
type: "mcp_server_census",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
server_name: key,
transport: remoteTransport,
tool_count: toolsList.tools.length,
resource_count: resourcesList.resources.length,
})
}).catch(() => {})
break
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error))
// Handle OAuth-specific errors.
// The SDK throws UnauthorizedError when auth() returns 'REDIRECT',
// but may also throw plain Errors when auth() fails internally
// (e.g. during discovery, registration, or state generation).
// When an authProvider is attached, treat both cases as auth-related.
const isAuthError =
error instanceof UnauthorizedError || (authProvider && lastError.message.includes("OAuth"))
if (isAuthError) {
log.info("mcp server requires authentication", { key, transport: name })
// Check if this is a "needs registration" error
if (lastError.message.includes("registration") || lastError.message.includes("client_id")) {
status = {
status: "needs_client_registration" as const,
error: "Server does not support dynamic client registration. Please provide clientId in config.",
}
// Show toast for needs_client_registration
Bus.publish(TuiEvent.ToastShow, {
title: "MCP Authentication Required",
message: `Server "${key}" requires a pre-registered client ID. Add clientId to your config.`,
variant: "warning",
duration: 8000,
}).catch((e) => log.debug("failed to show toast", { error: e }))
} else {
// Store transport for later finishAuth call
pendingOAuthTransports.set(key, transport)
status = { status: "needs_auth" as const }
// Show toast for needs_auth
Bus.publish(TuiEvent.ToastShow, {
title: "MCP Authentication Required",
message: `Server "${key}" requires authentication. Run: altimate mcp auth ${key}`,
variant: "warning",
duration: 8000,
}).catch((e) => log.debug("failed to show toast", { error: e }))
}
break
}
log.debug("transport connection failed", {
key,
transport: name,
url: mcp.url,
error: lastError.message,
})
Telemetry.track({
type: "mcp_server_status",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
server_name: key,
transport: name === "SSE" ? "sse" : "streamable-http",
status: "error",
error: lastError.message.slice(0, 500),
duration_ms: Date.now() - connectStart,
})
status = {
status: "failed" as const,
error: lastError.message,
}
}
}
}
if (mcp.type === "local") {
const [cmd, ...args] = mcp.command
const cwd = Instance.directory
const transport = new StdioClientTransport({
stderr: "pipe",
command: cmd,
args,
cwd,
env: {
...process.env,
...(cmd === "altimate" || cmd === "altimate-code" ? { BUN_BE_BUN: "1" } : {}),
// altimate_change start — env-var references in mcp.environment are resolved once
// at config load time: `ConfigPaths.substitute()` for `opencode.json`, and
// `resolveServerEnvVars()` for discovered external configs (`.vscode/mcp.json`,
// `.cursor/mcp.json`, etc.). A second pass here would re-expand already-resolved
// values and break the `$${VAR}` escape convention — see PR #666 review.
...(mcp.environment ?? {}),
// altimate_change end
},
})
transport.stderr?.on("data", (chunk: Buffer) => {
log.info(`mcp stderr: ${chunk.toString()}`, { key })
})
const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
const localConnectStart = Date.now()
try {
const client = new Client({
name: "altimate",
version: Installation.VERSION,
})
await withTimeout(client.connect(transport), connectTimeout)
registerNotificationHandlers(client, key)
mcpClient = client
connectedTransport = "stdio"
status = {
status: "connected",
}
Telemetry.track({
type: "mcp_server_status",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
server_name: key,
transport: "stdio",
status: "connected",
duration_ms: Date.now() - localConnectStart,
})
// Census: collect tool and resource counts (fire-and-forget, never block connect)
void Promise.all([
client.listTools().catch(() => ({ tools: [] })),
client.listResources().catch(() => ({ resources: [] })),
]).then(([toolsList, resourcesList]) => {
Telemetry.track({
type: "mcp_server_census",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
server_name: key,
transport: "stdio",
tool_count: toolsList.tools.length,
resource_count: resourcesList.resources.length,
})
}).catch(() => {})
} catch (error) {
log.error("local mcp startup failed", {
key,
command: mcp.command,
cwd,
error: error instanceof Error ? error.message : String(error),
})
const errorMsg = error instanceof Error ? error.message : String(error)
Telemetry.track({
type: "mcp_server_status",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
server_name: key,
transport: "stdio",
status: "error",
error: errorMsg.slice(0, 500),
duration_ms: Date.now() - localConnectStart,
})
status = {
status: "failed" as const,
error: errorMsg,
}
}
}
if (!status) {
status = {
status: "failed" as const,
error: "Unknown error",
}
}
if (!mcpClient) {
return {
mcpClient: undefined,
status,
}
}
const result = await withTimeout(mcpClient.listTools(), mcp.timeout ?? DEFAULT_TIMEOUT).catch((err) => {
log.error("failed to get tools from client", { key, error: err })
return undefined
})
if (!result) {
await mcpClient.close().catch((error) => {
log.error("Failed to close MCP client", {
error,
})
})
status = {
status: "failed",
error: "Failed to get tools",
}
return {
mcpClient: undefined,
status: {
status: "failed" as const,
error: "Failed to get tools",
},
}
}
log.info("create() successfully created client", { key, toolCount: result.tools.length })
return {
mcpClient,
status,
transport: connectedTransport,
}
}
export async function status() {
const s = await state()
const cfg = await Config.get()
const config = cfg.mcp ?? {}
const result: Record<string, Status> = {}
// Include all configured MCPs from config, not just connected ones
for (const [key, mcp] of Object.entries(config)) {
if (!isMcpConfigured(mcp)) continue
result[key] = s.status[key] ?? { status: "disabled" }
}
// Include dynamically added servers not yet in cached config
for (const [key, st] of Object.entries(s.status)) {
if (!(key in result)) {
result[key] = st
}
}
return result
}
export async function clients() {
return state().then((state) => state.clients)
}
export async function connect(name: string) {
const cfg = await Config.get()
const config = cfg.mcp ?? {}
const mcp = config[name]
if (!mcp) {
log.error("MCP config not found", { name })
return
}
if (!isMcpConfigured(mcp)) {
log.error("Ignoring MCP connect request for config without type", { name })
return
}
const result = await create(name, { ...mcp, enabled: true })
if (!result) {
const s = await state()
s.status[name] = {
status: "failed",
error: "Unknown error during connection",
}
return
}
const s = await state()
s.status[name] = result.status
if (result.mcpClient) {
// Close existing client if present to prevent memory leaks
const existingClient = s.clients[name]
if (existingClient) {
await existingClient.close().catch((error) => {
log.error("Failed to close existing MCP client", { name, error })
})
}
s.clients[name] = result.mcpClient
if (result.transport) s.transports[name] = result.transport
}
}
export async function disconnect(name: string) {
const s = await state()
const transport = s.transports[name] ?? "stdio"
const client = s.clients[name]
if (client) {
await client.close().catch((error) => {
log.error("Failed to close MCP client", { name, error })
})
delete s.clients[name]
}
Telemetry.track({
type: "mcp_server_status",
timestamp: Date.now(),
session_id: Telemetry.getContext().sessionId,
server_name: name,
transport,
status: "disconnected",
})
delete s.transports[name]
s.status[name] = { status: "disabled" }
}
/** Fully remove a dynamically-added MCP server — disconnects, and purges from runtime state. */
export async function remove(name: string) {
await disconnect(name)
const s = await state()
delete s.status[name]
Bus.publish(ToolsChanged, { server: name })
}
export async function tools() {
const result: Record<string, Tool> = {}
const s = await state()
const cfg = await Config.get()
const config = cfg.mcp ?? {}
const clientsSnapshot = await clients()
const defaultTimeout = cfg.experimental?.mcp_timeout
const connectedClients = Object.entries(clientsSnapshot).filter(
([clientName]) => s.status[clientName]?.status === "connected",
)
const toolsResults = await Promise.all(
connectedClients.map(async ([clientName, client]) => {
const toolsResult = await client.listTools().catch((e) => {
log.error("failed to get tools", { clientName, error: e.message })
const failedStatus = {
status: "failed" as const,
error: e instanceof Error ? e.message : String(e),
}
s.status[clientName] = failedStatus
delete s.clients[clientName]
return undefined
})
return { clientName, client, toolsResult }
}),
)
registeredMcpTools.clear()
for (const { clientName, client, toolsResult } of toolsResults) {
if (!toolsResult) continue
const mcpConfig = config[clientName]
const entry = isMcpConfigured(mcpConfig) ? mcpConfig : undefined
const timeout = entry?.timeout ?? defaultTimeout
for (const mcpTool of toolsResult.tools) {
const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
const sanitizedToolName = mcpTool.name.replace(/[^a-zA-Z0-9_-]/g, "_")
const toolName = sanitizedClientName + "_" + sanitizedToolName
registeredMcpTools.add(toolName)
result[toolName] = await convertMcpTool(mcpTool, client, timeout)
}
}
return result
}
export async function prompts() {
const s = await state()
const clientsSnapshot = await clients()
const prompts = Object.fromEntries<PromptInfo & { client: string }>(
(
await Promise.all(
Object.entries(clientsSnapshot).map(async ([clientName, client]) => {
if (s.status[clientName]?.status !== "connected") {
return []
}
return Object.entries((await fetchPromptsForClient(clientName, client)) ?? {})
}),
)
).flat(),
)
return prompts
}
export async function resources() {
const s = await state()
const clientsSnapshot = await clients()
const result = Object.fromEntries<ResourceInfo & { client: string }>(
(
await Promise.all(
Object.entries(clientsSnapshot).map(async ([clientName, client]) => {
if (s.status[clientName]?.status !== "connected") {
return []
}
return Object.entries((await fetchResourcesForClient(clientName, client)) ?? {})
}),
)
).flat(),
)
return result
}
export async function getPrompt(clientName: string, name: string, args?: Record<string, string>) {
const clientsSnapshot = await clients()
const client = clientsSnapshot[clientName]
if (!client) {
log.warn("client not found for prompt", {
clientName,
})
return undefined
}
const result = await client
.getPrompt({
name: name,
arguments: args,
})
.catch((e) => {
log.error("failed to get prompt from MCP server", {
clientName,
promptName: name,
error: e.message,
})
return undefined
})
return result
}
export async function readResource(clientName: string, resourceUri: string) {
const clientsSnapshot = await clients()
const client = clientsSnapshot[clientName]
if (!client) {
log.warn("client not found for resource", {
clientName: clientName,
})
return undefined
}
const result = await client
.readResource({
uri: resourceUri,
})
.catch((e) => {
log.error("failed to read resource from MCP server", {
clientName: clientName,
resourceUri: resourceUri,
error: e.message,
})
return undefined
})
return result
}
/**
* Start OAuth authentication flow for an MCP server.
* Returns the authorization URL that should be opened in a browser.
*/
export async function startAuth(mcpName: string): Promise<{ authorizationUrl: string }> {
const cfg = await Config.get()
const mcpConfig = cfg.mcp?.[mcpName]
if (!mcpConfig) {
throw new Error(`MCP server not found: ${mcpName}`)
}
if (!isMcpConfigured(mcpConfig)) {
throw new Error(`MCP server ${mcpName} is disabled or missing configuration`)
}
if (mcpConfig.type !== "remote") {
throw new Error(`MCP server ${mcpName} is not a remote server`)
}
if (mcpConfig.oauth === false) {
throw new Error(`MCP server ${mcpName} has OAuth explicitly disabled`)
}
// Start the callback server
await McpOAuthCallback.ensureRunning()
// Generate and store a cryptographically secure state parameter BEFORE creating the provider
// The SDK will call provider.state() to read this value
const oauthState = Array.from(crypto.getRandomValues(new Uint8Array(32)))
.map((b) => b.toString(16).padStart(2, "0"))
.join("")
await McpAuth.updateOAuthState(mcpName, oauthState)
// Create a new auth provider for this flow
// OAuth config is optional - if not provided, we'll use auto-discovery
const oauthConfig = typeof mcpConfig.oauth === "object" ? mcpConfig.oauth : undefined
let capturedUrl: URL | undefined
const authProvider = new McpOAuthProvider(
mcpName,
mcpConfig.url,
{
clientId: oauthConfig?.clientId,
clientSecret: oauthConfig?.clientSecret,
scope: oauthConfig?.scope,
},
{
onRedirect: async (url) => {
capturedUrl = url
},
},
)
// Create transport with auth provider
const transport = new StreamableHTTPClientTransport(new URL(mcpConfig.url), {
authProvider,
})
// Try to connect - this will trigger the OAuth flow
try {
const client = new Client({
name: "altimate",
version: Installation.VERSION,
})
await client.connect(transport)
// If we get here, we're already authenticated
return { authorizationUrl: "" }
} catch (error) {
if (error instanceof UnauthorizedError && capturedUrl) {
// Store transport for finishAuth
pendingOAuthTransports.set(mcpName, transport)
return { authorizationUrl: capturedUrl.toString() }
}
throw error
}
}
/**
* Complete OAuth authentication after user authorizes in browser.
* Opens the browser and waits for callback.
*/
export async function authenticate(mcpName: string): Promise<Status> {
const { authorizationUrl } = await startAuth(mcpName)
if (!authorizationUrl) {
// Already authenticated
const s = await state()
return s.status[mcpName] ?? { status: "connected" }
}
// Get the state that was already generated and stored in startAuth()
const oauthState = await McpAuth.getOAuthState(mcpName)
if (!oauthState) {
throw new Error("OAuth state not found - this should not happen")
}
// The SDK has already added the state parameter to the authorization URL
// We just need to open the browser
log.info("opening browser for oauth", { mcpName, url: authorizationUrl, state: oauthState })
// Register the callback BEFORE opening the browser to avoid race condition
// when the IdP has an active SSO session and redirects immediately
const callbackPromise = McpOAuthCallback.waitForCallback(oauthState)
try {
const subprocess = await open(authorizationUrl)
// The open package spawns a detached process and returns immediately.
// We need to listen for errors which fire asynchronously:
// - "error" event: command not found (ENOENT)
// - "exit" with non-zero code: command exists but failed (e.g., no display)
await new Promise<void>((resolve, reject) => {
// Give the process a moment to fail if it's going to
const timeout = setTimeout(() => resolve(), 500)
subprocess.on("error", (error) => {
clearTimeout(timeout)
reject(error)
})
subprocess.on("exit", (code) => {
if (code !== null && code !== 0) {
clearTimeout(timeout)
reject(new Error(`Browser open failed with exit code ${code}`))
}
})
})
} catch (error) {
// Browser opening failed (e.g., in remote/headless sessions like SSH, devcontainers)
// Emit event so CLI can display the URL for manual opening
log.warn("failed to open browser, user must open URL manually", { mcpName, error })
Bus.publish(BrowserOpenFailed, { mcpName, url: authorizationUrl })
}