-
Notifications
You must be signed in to change notification settings - Fork 0
feat: PR-A1 connection foundation — singleton + discovery + wait_for_reconnect #29
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
fe6a749
chore(deps): force vitest >=4.1.8 via overrides to resolve GHSA-5xrq-…
LSDimi 35bde12
chore(deps): bump vitest to ^4.1.8 across all workspaces
LSDimi b05373b
chore(deps): hoist vitest + @vitest/coverage-v8 to root devDependencies
LSDimi 63e8a8c
feat(mcp-server): add singleton types module
LSDimi 663963e
feat(mcp-server): add lockfile primitive with stale-PID detection
LSDimi 909eb68
feat(mcp-server): add pid-file r/w with atomic write
LSDimi cca8a3f
feat(mcp-server): add process takeover (SIGTERM → grace → SIGKILL)
LSDimi d0fcb30
feat(mcp-server): add state.json read/write helpers
LSDimi ea1c26e
feat(mcp-server): add singleton orchestrator (acquire + writeState + …
LSDimi 03e1526
test(mcp-server): add two-process singleton integration test
LSDimi 7137628
feat(mcp-server): wire singleton lock + state-file into startup
LSDimi a96b9d7
feat(mcp-server): add HTTP /state.json endpoint
LSDimi 09cbd06
feat(bridge-plugin): add discovery module
LSDimi b6f932b
feat(bridge-plugin): use ranked discovery before port scan in connect()
LSDimi cd6bd01
feat(mcp-server): add wait_for_reconnect MCP tool
LSDimi ca945ef
docs(claude-plugin): document wait_for_reconnect in skill troubleshoo…
LSDimi 27363df
style(mcp-server): drop unused buildStateFile import in singleton/ind…
LSDimi 6a9c96f
style: apply prettier formatting across singleton + index.ts
LSDimi 514b7b9
fix(mcp-server): apply Gemini review findings for PR-A1 connection fo…
LSDimi 13daba3
fix(bridge-plugin): drop .js extension from discovery import for webpack
LSDimi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; | ||
| import { | ||
| fetchStateJson, | ||
| rankCandidates, | ||
| discoverCandidatePorts, | ||
| type StateFile, | ||
| SUPPORTED_VERSION, | ||
| } from "../discovery.js"; | ||
|
|
||
| describe("fetchStateJson", () => { | ||
| beforeEach(() => { | ||
| vi.stubGlobal("fetch", vi.fn()); | ||
| }); | ||
| afterEach(() => { | ||
| vi.unstubAllGlobals(); | ||
| }); | ||
|
|
||
| it("returns parsed state on 200 with a supported version", async () => { | ||
| const state: StateFile = { | ||
| version: 1, | ||
| pid: 1234, | ||
| port: 9500, | ||
| serverVersion: "0.4.3", | ||
| startedAt: 100, | ||
| parentPid: 99, | ||
| parentAlive: true, | ||
| socketPath: null, | ||
| }; | ||
| (fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: async () => state, | ||
| }); | ||
| const result = await fetchStateJson(9500); | ||
| expect(result).toEqual(state); | ||
| }); | ||
|
|
||
| it("returns null on a non-200 response", async () => { | ||
| (fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: false }); | ||
| expect(await fetchStateJson(9500)).toBeNull(); | ||
| }); | ||
|
|
||
| it("returns null when fetch throws", async () => { | ||
| (fetch as unknown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("boom")); | ||
| expect(await fetchStateJson(9500)).toBeNull(); | ||
| }); | ||
|
|
||
| it("returns null for a future version", async () => { | ||
| (fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: async () => ({ version: SUPPORTED_VERSION + 1, pid: 1, port: 9500 }), | ||
| }); | ||
| expect(await fetchStateJson(9500)).toBeNull(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("rankCandidates", () => { | ||
| function makeState(overrides: Partial<StateFile>): StateFile { | ||
| return { | ||
| version: 1, | ||
| pid: 1, | ||
| port: 9500, | ||
| serverVersion: "0.4.3", | ||
| startedAt: 0, | ||
| parentPid: 99, | ||
| parentAlive: true, | ||
| socketPath: null, | ||
| ...overrides, | ||
| }; | ||
| } | ||
|
|
||
| it("filters out candidates with parentAlive=false", () => { | ||
| const ranked = rankCandidates([ | ||
| { port: 9500, state: makeState({ parentAlive: false, startedAt: 100 }) }, | ||
| { port: 9501, state: makeState({ parentAlive: true, startedAt: 50 }) }, | ||
| ]); | ||
| expect(ranked).toHaveLength(1); | ||
| expect(ranked[0].port).toBe(9501); | ||
| }); | ||
|
|
||
| it("sorts by startedAt descending (newest first)", () => { | ||
| const ranked = rankCandidates([ | ||
| { port: 9500, state: makeState({ startedAt: 100 }) }, | ||
| { port: 9501, state: makeState({ startedAt: 200 }) }, | ||
| { port: 9502, state: makeState({ startedAt: 150 }) }, | ||
| ]); | ||
| expect(ranked.map((c) => c.port)).toEqual([9501, 9502, 9500]); | ||
| }); | ||
| }); | ||
|
|
||
| describe("discoverCandidatePorts (probe-and-rank end-to-end)", () => { | ||
| beforeEach(() => { | ||
| vi.stubGlobal("fetch", vi.fn()); | ||
| }); | ||
| afterEach(() => { | ||
| vi.unstubAllGlobals(); | ||
| }); | ||
|
|
||
| it("returns ranked candidates, excluding orphans", async () => { | ||
| const orphan: StateFile = { | ||
| version: 1, | ||
| pid: 1, | ||
| port: 9500, | ||
| serverVersion: "0.4.3", | ||
| startedAt: 100, | ||
| parentPid: 99, | ||
| parentAlive: false, | ||
| socketPath: null, | ||
| }; | ||
| const live: StateFile = { | ||
| version: 1, | ||
| pid: 2, | ||
| port: 9501, | ||
| serverVersion: "0.4.3", | ||
| startedAt: 200, | ||
| parentPid: 100, | ||
| parentAlive: true, | ||
| socketPath: null, | ||
| }; | ||
| const fetchMock = fetch as unknown as ReturnType<typeof vi.fn>; | ||
| fetchMock.mockImplementation(async (url: string) => { | ||
| if (url.includes(":9500")) return { ok: true, json: async () => orphan }; | ||
| if (url.includes(":9501")) return { ok: true, json: async () => live }; | ||
| throw new Error("ECONNREFUSED"); | ||
| }); | ||
| const ranked = await discoverCandidatePorts([9500, 9501, 9502]); | ||
| expect(ranked).toHaveLength(1); | ||
| expect(ranked[0].port).toBe(9501); | ||
| }); | ||
|
|
||
| it("returns empty when no servers respond", async () => { | ||
| const fetchMock = fetch as unknown as ReturnType<typeof vi.fn>; | ||
| fetchMock.mockRejectedValue(new Error("ECONNREFUSED")); | ||
| const ranked = await discoverCandidatePorts([9500, 9501]); | ||
| expect(ranked).toEqual([]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| export interface StateFile { | ||
| version: 1; | ||
| pid: number; | ||
| port: number; | ||
| serverVersion: string; | ||
| startedAt: number; | ||
| parentPid: number; | ||
| parentAlive: boolean; | ||
| socketPath: string | null; | ||
| } | ||
|
|
||
| export const SUPPORTED_VERSION = 1; | ||
| export const FETCH_TIMEOUT_MS = 300; | ||
|
|
||
| export interface DiscoveryCandidate { | ||
| port: number; | ||
| state: StateFile; | ||
| } | ||
|
|
||
| export async function fetchStateJson(port: number): Promise<StateFile | null> { | ||
| try { | ||
| const controller = new AbortController(); | ||
| const t = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); | ||
| let res: Response; | ||
| try { | ||
| res = await fetch(`http://127.0.0.1:${port}/state.json`, { | ||
| signal: controller.signal, | ||
| }); | ||
| if (!res.ok) return null; | ||
| const body = (await res.json()) as unknown; | ||
| if ( | ||
| typeof body === "object" && | ||
| body !== null && | ||
| typeof (body as { version?: unknown }).version === "number" && | ||
| (body as { version: number }).version <= SUPPORTED_VERSION | ||
| ) { | ||
| return body as StateFile; | ||
| } | ||
| return null; | ||
| } finally { | ||
| clearTimeout(t); | ||
| } | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| export function rankCandidates(candidates: DiscoveryCandidate[]): DiscoveryCandidate[] { | ||
| return candidates | ||
| .filter((c) => c.state.parentAlive !== false) | ||
| .sort((a, b) => b.state.startedAt - a.state.startedAt); | ||
| } | ||
|
|
||
| export async function discoverCandidatePorts(ports: number[]): Promise<DiscoveryCandidate[]> { | ||
| const probed = await Promise.all( | ||
| ports.map(async (port) => { | ||
| const state = await fetchStateJson(port); | ||
| return state ? { port, state } : null; | ||
| }) | ||
| ); | ||
| const candidates = probed.filter((c): c is DiscoveryCandidate => c !== null); | ||
| return rankCandidates(candidates); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
47 changes: 47 additions & 0 deletions
47
packages/mcp-server/src/__tests__/http-state-endpoint.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import { describe, it, expect } from "vitest"; | ||
| import { createHttpServer } from "../http-server.js"; | ||
| import type { StateFile } from "../singleton/types.js"; | ||
|
|
||
| describe("HTTP /state.json endpoint", () => { | ||
| it("returns the current state object when set", async () => { | ||
| const state: StateFile = { | ||
| version: 1, | ||
| pid: 1234, | ||
| port: 9500, | ||
| serverVersion: "0.4.3", | ||
| startedAt: 1700000000000, | ||
| parentPid: 99, | ||
| parentAlive: true, | ||
| socketPath: null, | ||
| }; | ||
| const server = createHttpServer( | ||
| () => "<html></html>", | ||
| () => state | ||
| ); | ||
| await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r())); | ||
| const port = (server.address() as { port: number }).port; | ||
| try { | ||
| const res = await fetch(`http://127.0.0.1:${port}/state.json`); | ||
| expect(res.status).toBe(200); | ||
| const body = await res.json(); | ||
| expect(body).toEqual(state); | ||
| } finally { | ||
| server.close(); | ||
| } | ||
| }); | ||
|
|
||
| it("returns 503 when no state is set", async () => { | ||
| const server = createHttpServer( | ||
| () => "<html></html>", | ||
| () => null | ||
| ); | ||
| await new Promise<void>((r) => server.listen(0, "127.0.0.1", () => r())); | ||
| const port = (server.address() as { port: number }).port; | ||
| try { | ||
| const res = await fetch(`http://127.0.0.1:${port}/state.json`); | ||
| expect(res.status).toBe(503); | ||
| } finally { | ||
| server.close(); | ||
| } | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In
fetchStateJson, the timeouttis cleared on line 27, which is beforeawait res.json()is called. If the server responds to the initial HTTP headers quickly but hangs or sends the body extremely slowly,await res.json()could block indefinitely without any timeout protection.\n\nAdditionally, iffetchthrows an error (e.g.,ECONNREFUSED), the execution immediately jumps to thecatchblock, skippingclearTimeout(t)entirely and leaking the timer resource.\n\nWrapping the logic in atry...finallyblock and keeping the timeout active during the entire request (including the body read) solves both issues cleanly.