90e86a5e3d
* tweak: use theme tokens for debug bar surface * chore: update nix node_modules hashes * feat(tui): add heap snapshot functionality for TUI and server (#19028) * ci * change model for changelog * release: v1.3.2 * fix(opencode): skip typechecking generated models snapshot (#19018) * Revert "fix(app): more startup efficiency (#18985)" This reverts commit98b3340cee. * Revert "fix(app): startup efficiency (#18854)" This reverts commit546748a461. * effectify Worktree service (#18679) * fix: increase operations-per-run to 1000 and pin stale action to v10.2.0 The stale-issues workflow was hitting the default 30 operations limit, preventing it from processing all 2900+ issues/PRs. Increased to 1000 to handle the full backlog. Also pinned to exact v10.2.0 for reproducibility. * Add close-issues script and GitHub Action - Create script/github/close-issues.ts to close stale issues after 60 days - Add GitHub Action workflow to run daily at 2 AM - Remove old stale-issues workflow to avoid conflicts * Fix close-issues workflow permissions - Add contents: read permission for checkout - Use github.token instead of secrets.GITHUB_TOKEN * Process issues sequentially to avoid rate limits * Change issue close reason from not_planned to completed * fix(opencode): avoid snapshotting files over 2MB (#19043) * fix: provide merge context to beta conflict resolver (#19055) * tweak: only spawn lsp servers for files in current instance (or cwd if instance is global) (#19058) * fix: beta resolver typecheck + build smoke check (#19060) * fix: unblock beta conflict recovery (#19068) * electron: add createDirectory to open directory picker (#19071) * electron: remove file extension from electron-store wrapper (#19082) * app: pre-warm project globalSync state when navigate project via keybind (#19088) * fix(app): move message navigation off cmd+arrow (#18728) * Reapply "fix(app): startup efficiency (#18854)" This reverts commita379eb3867. * Reapply "fix(app): more startup efficiency (#18985)" This reverts commitcbe1337f24. * fix(app): hash inline script for csp * Revert "fix(app): startup efficiency" * Reapply "fix(app): startup efficiency" This reverts commit898456a25c. * fix(app): opencode web server url * chore(app): markdown playground in storyboard * chore(app): markdown playground in storyboard * feat(core): initial implementation of syncing (#17814) * chore: generate * chore: bump modelcontextprotocol/sdk to 1.27.1 (#19064) * chore: storybook tweaks * feat: restore git-backed review modes with effectful git service (#18900) * chore: generate * chore: update nix node_modules hashes * chore: cleanup * chore: remove dead code for todoread tool (#19128) * chore: storybook tweaks * fix(opencode): classify ZlibError from Bun fetch as retryable instead of unknown (#19104) Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> * fix(task): respect agent permission config for todowrite tool (#19125) * fix(app): agent normalization (#19169) * fix: Windows e2e stability (CrossSpawnSpawner, snapshot isolation, session race guards) (#19163) * fix+refactor(mcp): lifecycle tests, cancelPending fix, Effect migration (#19042) * effectify Bus service: migrate to Effect PubSub + InstanceState (#18579) * file: use Effect.cached for scan deduplication (#19164) * ignore: update disavowed list (#19184) * skill: use Effect.cached for load deduplication (#19165) * chore: generate * fix: bump gitlab-ai-provider to 5.3.3 for DWS tool approval support (#19185) * test: restore 5 workers on Windows e2e (#19188) * fix(opencode): image paste on Windows Terminal 1.25+ with kitty keyboard (#17674) * chore: update nix node_modules hashes * wip: zen * wip: zen * go: do not respect disabled zen models * fix: ensure enterprise url is set properly during auth flow (#19212) * revert: roll back git-backed review modes (#19295) * chore: generate * tui: bypass local SSE event streaming in worker (#19183) * feat: embed WebUI in binary with proxy flags (#19299) Co-authored-by: BlankParticle <blankparticle@gmail.com> * release: v1.3.3 * chore: generate * changelog ci tweaks * refactor(lsp): effectify LSP service with InstanceState (#19150) * chore: generate * feat: add gpt prompt so non codex gpt models have their own system prompt modeled after codex cli (#19220) * feat(core): remove workspace server, WorkspaceContext, start work towards better routing (#19316) * effectify Config service (#19139) * chore: generate * refactor(config): use cachedInvalidateWithTTL, bump effect to beta.37 (#19322) * fix(mcp): close transport on failed/timed-out connections (#19200) * fix(app): more startup perf (#19288) * chore: generate * chore: update nix node_modules hashes * fix(app): don't bundle fonts (#19329) * chore: generate * fix(app): default shell tool to collapsed * fix(app): remove fork session button * fix(ui): reduce markdown jank while responses stream (#19304) * fix: web ui bundle build on windows (#19337) * refactor(effect): yield services instead of promise facades (#19325) * chore: generate * refactor(vcs): replace async git() with ChildProcessSpawner (#19361) * fix(opencode): ignore generated models snapshot files (#19362) * fix(ui): keep partial markdown readable while responses stream (#19403) * chore: update nix node_modules hashes * fix(app): persist queued followups across project switches (#19421) * refactor(tool-registry): yield Config/Plugin services, use Effect.forEach (#19363) * chore: generate * tui plugins (#19347) * chore: generate * effectify Skill service internals (#19364) * chore: update nix node_modules hashes * effectify Plugin service internals (#19365) * refactor(core): split out instance and route through workspaces (#19335) * chore(app): more spacing controls * fix(ui): make streamed markdown feel more continuous (#19404) * fix(app): resize layout viewport when mobile keyboard appears (#15841) * fix(desktop-electron): match dev dock icon inset on macOS (#19429) * fix(app): default file tree to closed with minimum width (#19426) * fix flaky plugin tests (no mock.module for bun) (#19445) * tweak: add additional overflow error patterns (#19446) * no theme override in dev (#19456) * feat: AI SDK v6 support (#18433) * refactor(session): effectify Session service (#19449) * refactor(core): move more responsibility to workspace routing (#19455) * chore: update nix node_modules hashes * refactor(format): use ChildProcessSpawner instead of Process.spawn (#19457) * chore: generate * Single target plugin entrypoints (#19467) * refactor(session): effectify SessionCompaction service (#19459) * feat(ci): use Azure Artifact Signing for Windows releases (#15201) * fix(app): more startup efficiency (#19454) * update effect to 4.0.0-beta.42 (#19484) * chore: update nix node_modules hashes * tweak: adjust bash tool description to increase cache hit rates between projects (#19487) * refactor(session): move context into prompt footer (#19486) * refactor(prompt): remove variant cycle display from footer (#19489) * feat: add model variant selection dialog (#19488) * fix: restore subagent footer and fix style guide violations (#19491) * tweak(session): add top spacing and remove obsolete docs prompt * upgrade opentui to 0.1.91 (#19440) * refactor(file): use AppFileSystem instead of raw Filesystem (#19458) * chore: generate * chore: update nix node_modules hashes * kv theme before default fallback (#19523) * feat: open dialog for model variant selection instead of cycling (#19534) * refactor(session): effectify session processor (#19485) * feat: dialog variant menu and subagent improvements (#19537) * use theme color for prompt placeholder (#19535) * fix: update opencode-gitlab-auth to 2.0.1 (#19552) * chore: update nix node_modules hashes * prompt slot (#19563) * fix: respect semver build identifiers for nix (#11915) * fix: nix embedded web-ui support (#19561) * ignore: kill todo (#19566) * chore: update nix node_modules hashes * wip: zen * wip: zen * zen: ZDR policy * ci: cancel stale nix-hashes runs (#19571) * release: v1.3.4 * refactor: kilo compat for v1.3.4 * fix: migration types * refactor: upgrade kilo-gateway to ai sdk v6 * refactor: improve upstream merge script * fix: fix some tests * style(kilo-vscode): adjust indentation and formatting in parts-util and PopupSelector Normalize boolean expression indentation in isCompletionResult to use consistent 4-space alignment and reformat PopupSelectorProps generic interface declaration to split the Omit type across multiple lines. * docs(kilo-docs): update auto-generated source links Remove outdated URLs and add new bug report issue link pointing to anomalyco/opencode repository. Drop references to kilocode bug report template and config precedence order docs, reducing total unique URLs from 262 to 261. * fix(kilo-ui): remove unused NerdFonts story and MONO_NERD_FONTS import Drop the NerdFonts story from font.stories.tsx along with the unused MONO_NERD_FONTS import, as the exported constant is no longer available from the @opencode-ai/ui/font module. * chore: update visual regression baselines * fix(opencode): move Show conditional wrapper outside box in home onboarding Relocate the Show component to wrap the box element instead of being nested inside it, preventing the empty box from rendering when the onboarding tip is not visible. --------- Co-authored-by: Jay V <air@live.ca> Co-authored-by: opencode-agent[bot] <opencode-agent[bot]@users.noreply.github.com> Co-authored-by: Dax <mail@thdxr.com> Co-authored-by: Dax Raad <d@ironbay.co> Co-authored-by: opencode <opencode@sst.dev> Co-authored-by: Kit Langton <kit.langton@gmail.com> Co-authored-by: Adam <2363879+adamdotdevin@users.noreply.github.com> Co-authored-by: Luke Parker <10430890+Hona@users.noreply.github.com> Co-authored-by: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Co-authored-by: Brendan Allan <brendonovich@outlook.com> Co-authored-by: Shoubhit Dash <shoubhit2005@gmail.com> Co-authored-by: James Long <longster@gmail.com> Co-authored-by: André Cruz <acruz@cloudflare.com> Co-authored-by: Ariane Emory <97994360+ariane-emory@users.noreply.github.com> Co-authored-by: Vladimir Glafirov <vglafirov@gitlab.com> Co-authored-by: Frank <frank@anoma.ly> Co-authored-by: BlankParticle <blankparticle@gmail.com> Co-authored-by: Sebastian <hasta84@gmail.com> Co-authored-by: Burak Yigit Kaya <byk@sentry.io> Co-authored-by: Caleb Norton <n0603919@outlook.com> Co-authored-by: Imanol Maiztegui <imanol.mzd@gmail.com> Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
751 lines
23 KiB
TypeScript
751 lines
23 KiB
TypeScript
import { test, expect, mock, beforeEach } from "bun:test"
|
|
|
|
// --- Mock infrastructure ---
|
|
|
|
// Per-client state for controlling mock behavior
|
|
interface MockClientState {
|
|
tools: Array<{ name: string; description?: string; inputSchema: object }>
|
|
listToolsCalls: number
|
|
listToolsShouldFail: boolean
|
|
listToolsError: string
|
|
listPromptsShouldFail: boolean
|
|
listResourcesShouldFail: boolean
|
|
prompts: Array<{ name: string; description?: string }>
|
|
resources: Array<{ name: string; uri: string; description?: string }>
|
|
closed: boolean
|
|
notificationHandlers: Map<unknown, (...args: any[]) => any>
|
|
}
|
|
|
|
const clientStates = new Map<string, MockClientState>()
|
|
let lastCreatedClientName: string | undefined
|
|
let connectShouldFail = false
|
|
let connectShouldHang = false
|
|
let connectError = "Mock transport cannot connect"
|
|
// Tracks how many Client instances were created (detects leaks)
|
|
let clientCreateCount = 0
|
|
// Tracks how many times transport.close() is called across all mock transports
|
|
let transportCloseCount = 0
|
|
|
|
function getOrCreateClientState(name?: string): MockClientState {
|
|
const key = name ?? "default"
|
|
let state = clientStates.get(key)
|
|
if (!state) {
|
|
state = {
|
|
tools: [{ name: "test_tool", description: "A test tool", inputSchema: { type: "object", properties: {} } }],
|
|
listToolsCalls: 0,
|
|
listToolsShouldFail: false,
|
|
listToolsError: "listTools failed",
|
|
listPromptsShouldFail: false,
|
|
listResourcesShouldFail: false,
|
|
prompts: [],
|
|
resources: [],
|
|
closed: false,
|
|
notificationHandlers: new Map(),
|
|
}
|
|
clientStates.set(key, state)
|
|
}
|
|
return state
|
|
}
|
|
|
|
// Mock transport that succeeds or fails based on connectShouldFail / connectShouldHang
|
|
class MockStdioTransport {
|
|
stderr: null = null
|
|
pid = 12345
|
|
constructor(_opts: any) {}
|
|
async start() {
|
|
if (connectShouldHang) return new Promise<void>(() => {}) // never resolves
|
|
if (connectShouldFail) throw new Error(connectError)
|
|
}
|
|
async close() {
|
|
transportCloseCount++
|
|
}
|
|
}
|
|
|
|
class MockStreamableHTTP {
|
|
constructor(_url: URL, _opts?: any) {}
|
|
async start() {
|
|
if (connectShouldHang) return new Promise<void>(() => {}) // never resolves
|
|
if (connectShouldFail) throw new Error(connectError)
|
|
}
|
|
async close() {
|
|
transportCloseCount++
|
|
}
|
|
async finishAuth() {}
|
|
}
|
|
|
|
class MockSSE {
|
|
constructor(_url: URL, _opts?: any) {}
|
|
async start() {
|
|
if (connectShouldHang) return new Promise<void>(() => {}) // never resolves
|
|
if (connectShouldFail) throw new Error(connectError)
|
|
}
|
|
async close() {
|
|
transportCloseCount++
|
|
}
|
|
}
|
|
|
|
mock.module("@modelcontextprotocol/sdk/client/stdio.js", () => ({
|
|
StdioClientTransport: MockStdioTransport,
|
|
}))
|
|
|
|
mock.module("@modelcontextprotocol/sdk/client/streamableHttp.js", () => ({
|
|
StreamableHTTPClientTransport: MockStreamableHTTP,
|
|
}))
|
|
|
|
mock.module("@modelcontextprotocol/sdk/client/sse.js", () => ({
|
|
SSEClientTransport: MockSSE,
|
|
}))
|
|
|
|
mock.module("@modelcontextprotocol/sdk/client/auth.js", () => ({
|
|
UnauthorizedError: class extends Error {
|
|
constructor() {
|
|
super("Unauthorized")
|
|
}
|
|
},
|
|
}))
|
|
|
|
// Mock Client that delegates to per-name MockClientState
|
|
mock.module("@modelcontextprotocol/sdk/client/index.js", () => ({
|
|
Client: class MockClient {
|
|
_state!: MockClientState
|
|
transport: any
|
|
|
|
constructor(_opts: any) {
|
|
clientCreateCount++
|
|
}
|
|
|
|
async connect(transport: { start: () => Promise<void> }) {
|
|
this.transport = transport
|
|
await transport.start()
|
|
// After successful connect, bind to the last-created client name
|
|
this._state = getOrCreateClientState(lastCreatedClientName)
|
|
}
|
|
|
|
setNotificationHandler(schema: unknown, handler: (...args: any[]) => any) {
|
|
this._state?.notificationHandlers.set(schema, handler)
|
|
}
|
|
|
|
async listTools() {
|
|
if (this._state) this._state.listToolsCalls++
|
|
if (this._state?.listToolsShouldFail) {
|
|
throw new Error(this._state.listToolsError)
|
|
}
|
|
return { tools: this._state?.tools ?? [] }
|
|
}
|
|
|
|
async listPrompts() {
|
|
if (this._state?.listPromptsShouldFail) {
|
|
throw new Error("listPrompts failed")
|
|
}
|
|
return { prompts: this._state?.prompts ?? [] }
|
|
}
|
|
|
|
async listResources() {
|
|
if (this._state?.listResourcesShouldFail) {
|
|
throw new Error("listResources failed")
|
|
}
|
|
return { resources: this._state?.resources ?? [] }
|
|
}
|
|
|
|
async close() {
|
|
if (this._state) this._state.closed = true
|
|
}
|
|
},
|
|
}))
|
|
|
|
beforeEach(() => {
|
|
clientStates.clear()
|
|
lastCreatedClientName = undefined
|
|
connectShouldFail = false
|
|
connectShouldHang = false
|
|
connectError = "Mock transport cannot connect"
|
|
clientCreateCount = 0
|
|
transportCloseCount = 0
|
|
})
|
|
|
|
// Import after mocks
|
|
const { MCP } = await import("../../src/mcp/index")
|
|
const { Instance } = await import("../../src/project/instance")
|
|
const { tmpdir } = await import("../fixture/fixture")
|
|
|
|
// --- Helper ---
|
|
|
|
function withInstance(config: Record<string, any>, fn: () => Promise<void>) {
|
|
return async () => {
|
|
await using tmp = await tmpdir({
|
|
init: async (dir) => {
|
|
await Bun.write(
|
|
`${dir}/opencode.json`,
|
|
JSON.stringify({
|
|
$schema: "https://opencode.ai/config.json",
|
|
mcp: config,
|
|
}),
|
|
)
|
|
},
|
|
})
|
|
|
|
await Instance.provide({
|
|
directory: tmp.path,
|
|
fn: async () => {
|
|
await fn()
|
|
// dispose instance to clean up state between tests
|
|
await Instance.dispose()
|
|
},
|
|
})
|
|
}
|
|
}
|
|
|
|
// ========================================================================
|
|
// Test: tools() are cached after connect
|
|
// ========================================================================
|
|
|
|
test(
|
|
"tools() reuses cached tool definitions after connect",
|
|
withInstance({}, async () => {
|
|
lastCreatedClientName = "my-server"
|
|
const serverState = getOrCreateClientState("my-server")
|
|
serverState.tools = [
|
|
{ name: "do_thing", description: "does a thing", inputSchema: { type: "object", properties: {} } },
|
|
]
|
|
|
|
// First: add the server successfully
|
|
const addResult = await MCP.add("my-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
expect((addResult.status as any)["my-server"]?.status ?? (addResult.status as any).status).toBe("connected")
|
|
|
|
expect(serverState.listToolsCalls).toBe(1)
|
|
|
|
const toolsA = await MCP.tools()
|
|
const toolsB = await MCP.tools()
|
|
expect(Object.keys(toolsA).length).toBeGreaterThan(0)
|
|
expect(Object.keys(toolsB).length).toBeGreaterThan(0)
|
|
expect(serverState.listToolsCalls).toBe(1)
|
|
}),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: tool change notifications refresh the cache
|
|
// ========================================================================
|
|
|
|
test(
|
|
"tool change notifications refresh cached tool definitions",
|
|
withInstance({}, async () => {
|
|
lastCreatedClientName = "status-server"
|
|
const serverState = getOrCreateClientState("status-server")
|
|
|
|
await MCP.add("status-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
const before = await MCP.tools()
|
|
expect(Object.keys(before).some((key) => key.includes("test_tool"))).toBe(true)
|
|
expect(serverState.listToolsCalls).toBe(1)
|
|
|
|
serverState.tools = [{ name: "next_tool", description: "next", inputSchema: { type: "object", properties: {} } }]
|
|
|
|
const handler = Array.from(serverState.notificationHandlers.values())[0]
|
|
expect(handler).toBeDefined()
|
|
await handler?.()
|
|
|
|
const after = await MCP.tools()
|
|
expect(Object.keys(after).some((key) => key.includes("next_tool"))).toBe(true)
|
|
expect(Object.keys(after).some((key) => key.includes("test_tool"))).toBe(false)
|
|
expect(serverState.listToolsCalls).toBe(2)
|
|
}),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: connect() / disconnect() lifecycle
|
|
// ========================================================================
|
|
|
|
test(
|
|
"disconnect sets status to disabled and removes client",
|
|
withInstance(
|
|
{
|
|
"disc-server": {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
},
|
|
},
|
|
async () => {
|
|
lastCreatedClientName = "disc-server"
|
|
getOrCreateClientState("disc-server")
|
|
|
|
await MCP.add("disc-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
const statusBefore = await MCP.status()
|
|
expect(statusBefore["disc-server"]?.status).toBe("connected")
|
|
|
|
await MCP.disconnect("disc-server")
|
|
|
|
const statusAfter = await MCP.status()
|
|
expect(statusAfter["disc-server"]?.status).toBe("disabled")
|
|
|
|
// Tools should be empty after disconnect
|
|
const tools = await MCP.tools()
|
|
const serverTools = Object.keys(tools).filter((k) => k.startsWith("disc-server"))
|
|
expect(serverTools.length).toBe(0)
|
|
},
|
|
),
|
|
)
|
|
|
|
test(
|
|
"connect() after disconnect() re-establishes the server",
|
|
withInstance(
|
|
{
|
|
"reconn-server": {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
},
|
|
},
|
|
async () => {
|
|
lastCreatedClientName = "reconn-server"
|
|
const serverState = getOrCreateClientState("reconn-server")
|
|
serverState.tools = [{ name: "my_tool", description: "a tool", inputSchema: { type: "object", properties: {} } }]
|
|
|
|
await MCP.add("reconn-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
await MCP.disconnect("reconn-server")
|
|
expect((await MCP.status())["reconn-server"]?.status).toBe("disabled")
|
|
|
|
// Reconnect
|
|
await MCP.connect("reconn-server")
|
|
expect((await MCP.status())["reconn-server"]?.status).toBe("connected")
|
|
|
|
const tools = await MCP.tools()
|
|
expect(Object.keys(tools).some((k) => k.includes("my_tool"))).toBe(true)
|
|
},
|
|
),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: add() closes existing client before replacing
|
|
// ========================================================================
|
|
|
|
test(
|
|
"add() closes the old client when replacing a server",
|
|
// Don't put the server in config — add it dynamically so we control
|
|
// exactly which client instance is "first" vs "second".
|
|
withInstance({}, async () => {
|
|
lastCreatedClientName = "replace-server"
|
|
const firstState = getOrCreateClientState("replace-server")
|
|
|
|
await MCP.add("replace-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
expect(firstState.closed).toBe(false)
|
|
|
|
// Create new state for second client
|
|
clientStates.delete("replace-server")
|
|
const secondState = getOrCreateClientState("replace-server")
|
|
|
|
// Re-add should close the first client
|
|
await MCP.add("replace-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
expect(firstState.closed).toBe(true)
|
|
expect(secondState.closed).toBe(false)
|
|
}),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: state init with mixed success/failure
|
|
// ========================================================================
|
|
|
|
test(
|
|
"init connects available servers even when one fails",
|
|
withInstance(
|
|
{
|
|
"good-server": {
|
|
type: "local",
|
|
command: ["echo", "good"],
|
|
},
|
|
"bad-server": {
|
|
type: "local",
|
|
command: ["echo", "bad"],
|
|
},
|
|
},
|
|
async () => {
|
|
// Set up good server
|
|
const goodState = getOrCreateClientState("good-server")
|
|
goodState.tools = [{ name: "good_tool", description: "works", inputSchema: { type: "object", properties: {} } }]
|
|
|
|
// Set up bad server - will fail on listTools during create()
|
|
const badState = getOrCreateClientState("bad-server")
|
|
badState.listToolsShouldFail = true
|
|
|
|
// Add good server first
|
|
lastCreatedClientName = "good-server"
|
|
await MCP.add("good-server", {
|
|
type: "local",
|
|
command: ["echo", "good"],
|
|
})
|
|
|
|
// Add bad server - should fail but not affect good server
|
|
lastCreatedClientName = "bad-server"
|
|
await MCP.add("bad-server", {
|
|
type: "local",
|
|
command: ["echo", "bad"],
|
|
})
|
|
|
|
const status = await MCP.status()
|
|
expect(status["good-server"]?.status).toBe("connected")
|
|
expect(status["bad-server"]?.status).toBe("failed")
|
|
|
|
// Good server's tools should still be available
|
|
const tools = await MCP.tools()
|
|
expect(Object.keys(tools).some((k) => k.includes("good_tool"))).toBe(true)
|
|
},
|
|
),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: disabled server via config
|
|
// ========================================================================
|
|
|
|
test(
|
|
"disabled server is marked as disabled without attempting connection",
|
|
withInstance(
|
|
{
|
|
"disabled-server": {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
enabled: false,
|
|
},
|
|
},
|
|
async () => {
|
|
const countBefore = clientCreateCount
|
|
|
|
await MCP.add("disabled-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
enabled: false,
|
|
} as any)
|
|
|
|
// No client should have been created
|
|
expect(clientCreateCount).toBe(countBefore)
|
|
|
|
const status = await MCP.status()
|
|
expect(status["disabled-server"]?.status).toBe("disabled")
|
|
},
|
|
),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: prompts() and resources()
|
|
// ========================================================================
|
|
|
|
test(
|
|
"prompts() returns prompts from connected servers",
|
|
withInstance(
|
|
{
|
|
"prompt-server": {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
},
|
|
},
|
|
async () => {
|
|
lastCreatedClientName = "prompt-server"
|
|
const serverState = getOrCreateClientState("prompt-server")
|
|
serverState.prompts = [{ name: "my-prompt", description: "A test prompt" }]
|
|
|
|
await MCP.add("prompt-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
const prompts = await MCP.prompts()
|
|
expect(Object.keys(prompts).length).toBe(1)
|
|
const key = Object.keys(prompts)[0]
|
|
expect(key).toContain("prompt-server")
|
|
expect(key).toContain("my-prompt")
|
|
},
|
|
),
|
|
)
|
|
|
|
test(
|
|
"resources() returns resources from connected servers",
|
|
withInstance(
|
|
{
|
|
"resource-server": {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
},
|
|
},
|
|
async () => {
|
|
lastCreatedClientName = "resource-server"
|
|
const serverState = getOrCreateClientState("resource-server")
|
|
serverState.resources = [{ name: "my-resource", uri: "file:///test.txt", description: "A test resource" }]
|
|
|
|
await MCP.add("resource-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
const resources = await MCP.resources()
|
|
expect(Object.keys(resources).length).toBe(1)
|
|
const key = Object.keys(resources)[0]
|
|
expect(key).toContain("resource-server")
|
|
expect(key).toContain("my-resource")
|
|
},
|
|
),
|
|
)
|
|
|
|
test(
|
|
"prompts() skips disconnected servers",
|
|
withInstance(
|
|
{
|
|
"prompt-disc-server": {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
},
|
|
},
|
|
async () => {
|
|
lastCreatedClientName = "prompt-disc-server"
|
|
const serverState = getOrCreateClientState("prompt-disc-server")
|
|
serverState.prompts = [{ name: "hidden-prompt", description: "Should not appear" }]
|
|
|
|
await MCP.add("prompt-disc-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
await MCP.disconnect("prompt-disc-server")
|
|
|
|
const prompts = await MCP.prompts()
|
|
expect(Object.keys(prompts).length).toBe(0)
|
|
},
|
|
),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: connect() on nonexistent server
|
|
// ========================================================================
|
|
|
|
test(
|
|
"connect() on nonexistent server does not throw",
|
|
withInstance({}, async () => {
|
|
// Should not throw
|
|
await MCP.connect("nonexistent")
|
|
const status = await MCP.status()
|
|
expect(status["nonexistent"]).toBeUndefined()
|
|
}),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: disconnect() on nonexistent server
|
|
// ========================================================================
|
|
|
|
test(
|
|
"disconnect() on nonexistent server does not throw",
|
|
withInstance({}, async () => {
|
|
await MCP.disconnect("nonexistent")
|
|
// Should complete without error
|
|
}),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: tools() with no MCP servers configured
|
|
// ========================================================================
|
|
|
|
test(
|
|
"tools() returns empty when no MCP servers are configured",
|
|
withInstance({}, async () => {
|
|
const tools = await MCP.tools()
|
|
expect(Object.keys(tools).length).toBe(0)
|
|
}),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: connect failure during create()
|
|
// ========================================================================
|
|
|
|
test(
|
|
"server that fails to connect is marked as failed",
|
|
withInstance(
|
|
{
|
|
"fail-connect": {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
},
|
|
},
|
|
async () => {
|
|
lastCreatedClientName = "fail-connect"
|
|
getOrCreateClientState("fail-connect")
|
|
connectShouldFail = true
|
|
connectError = "Connection refused"
|
|
|
|
await MCP.add("fail-connect", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
const status = await MCP.status()
|
|
expect(status["fail-connect"]?.status).toBe("failed")
|
|
if (status["fail-connect"]?.status === "failed") {
|
|
expect(status["fail-connect"].error).toContain("Connection refused")
|
|
}
|
|
|
|
// No tools should be available
|
|
const tools = await MCP.tools()
|
|
expect(Object.keys(tools).length).toBe(0)
|
|
},
|
|
),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Bug #5: McpOAuthCallback.cancelPending uses wrong key
|
|
// ========================================================================
|
|
|
|
test("McpOAuthCallback.cancelPending is keyed by mcpName but pendingAuths uses oauthState", async () => {
|
|
const { McpOAuthCallback } = await import("../../src/mcp/oauth-callback")
|
|
|
|
// Register a pending auth with an oauthState key, associated to an mcpName
|
|
const oauthState = "abc123hexstate"
|
|
const callbackPromise = McpOAuthCallback.waitForCallback(oauthState, "my-mcp-server")
|
|
|
|
// cancelPending is called with mcpName — should find the entry via reverse index
|
|
McpOAuthCallback.cancelPending("my-mcp-server")
|
|
|
|
// The callback should still be pending because cancelPending looked up
|
|
// "my-mcp-server" in a map keyed by "abc123hexstate"
|
|
let resolved = false
|
|
let rejected = false
|
|
callbackPromise.then(() => (resolved = true)).catch(() => (rejected = true))
|
|
|
|
// Give it a tick
|
|
await new Promise((r) => setTimeout(r, 50))
|
|
|
|
// cancelPending("my-mcp-server") should have rejected the pending callback
|
|
expect(rejected).toBe(true)
|
|
|
|
await McpOAuthCallback.stop()
|
|
})
|
|
|
|
// ========================================================================
|
|
// Test: multiple tools from same server get correct name prefixes
|
|
// ========================================================================
|
|
|
|
test(
|
|
"tools() prefixes tool names with sanitized server name",
|
|
withInstance(
|
|
{
|
|
"my.special-server": {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
},
|
|
},
|
|
async () => {
|
|
lastCreatedClientName = "my.special-server"
|
|
const serverState = getOrCreateClientState("my.special-server")
|
|
serverState.tools = [
|
|
{ name: "tool-a", description: "Tool A", inputSchema: { type: "object", properties: {} } },
|
|
{ name: "tool.b", description: "Tool B", inputSchema: { type: "object", properties: {} } },
|
|
]
|
|
|
|
await MCP.add("my.special-server", {
|
|
type: "local",
|
|
command: ["echo", "test"],
|
|
})
|
|
|
|
const tools = await MCP.tools()
|
|
const keys = Object.keys(tools)
|
|
|
|
// Server name dots should be replaced with underscores
|
|
expect(keys.some((k) => k.startsWith("my_special-server_"))).toBe(true)
|
|
// Tool name dots should be replaced with underscores
|
|
expect(keys.some((k) => k.endsWith("tool_b"))).toBe(true)
|
|
expect(keys.length).toBe(2)
|
|
},
|
|
),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: transport leak — local stdio timeout (#19168)
|
|
// ========================================================================
|
|
|
|
test(
|
|
"local stdio transport is closed when connect times out (no process leak)",
|
|
withInstance({}, async () => {
|
|
lastCreatedClientName = "hanging-server"
|
|
getOrCreateClientState("hanging-server")
|
|
connectShouldHang = true
|
|
|
|
const addResult = await MCP.add("hanging-server", {
|
|
type: "local",
|
|
command: ["node", "fake.js"],
|
|
timeout: 100,
|
|
})
|
|
|
|
const serverStatus = (addResult.status as any)["hanging-server"] ?? addResult.status
|
|
expect(serverStatus.status).toBe("failed")
|
|
expect(serverStatus.error).toContain("timed out")
|
|
// Transport must be closed to avoid orphaned child process
|
|
expect(transportCloseCount).toBeGreaterThanOrEqual(1)
|
|
}),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: transport leak — remote timeout (#19168)
|
|
// ========================================================================
|
|
|
|
test(
|
|
"remote transport is closed when connect times out",
|
|
withInstance({}, async () => {
|
|
lastCreatedClientName = "hanging-remote"
|
|
getOrCreateClientState("hanging-remote")
|
|
connectShouldHang = true
|
|
|
|
const addResult = await MCP.add("hanging-remote", {
|
|
type: "remote",
|
|
url: "http://localhost:9999/mcp",
|
|
timeout: 100,
|
|
oauth: false,
|
|
})
|
|
|
|
const serverStatus = (addResult.status as any)["hanging-remote"] ?? addResult.status
|
|
expect(serverStatus.status).toBe("failed")
|
|
// Transport must be closed to avoid leaked HTTP connections
|
|
expect(transportCloseCount).toBeGreaterThanOrEqual(1)
|
|
}),
|
|
)
|
|
|
|
// ========================================================================
|
|
// Test: transport leak — failed remote transports not closed (#19168)
|
|
// ========================================================================
|
|
|
|
test(
|
|
"failed remote transport is closed before trying next transport",
|
|
withInstance({}, async () => {
|
|
lastCreatedClientName = "fail-remote"
|
|
getOrCreateClientState("fail-remote")
|
|
connectShouldFail = true
|
|
connectError = "Connection refused"
|
|
|
|
const addResult = await MCP.add("fail-remote", {
|
|
type: "remote",
|
|
url: "http://localhost:9999/mcp",
|
|
timeout: 5000,
|
|
oauth: false,
|
|
})
|
|
|
|
const serverStatus = (addResult.status as any)["fail-remote"] ?? addResult.status
|
|
expect(serverStatus.status).toBe("failed")
|
|
// Both StreamableHTTP and SSE transports should be closed
|
|
expect(transportCloseCount).toBeGreaterThanOrEqual(2)
|
|
}),
|
|
)
|