Skip to content

MCP server: add true E2E tests with real protocol client #414

Closed

Description

@admarble

Problem

The MCP server has solid test coverage (unit tests in `src/mcp/.test.ts`, integration tests in `tests/integration/mcp-serve.test.ts`), but every test uses either mocked child processes or `InMemoryTransport`. No test exercises the full path:

Real MCP Client → stdio/SSE protocol → sequant serve → tool handler → CLI subprocess → response

This means the following are untested end-to-end:

Gaps

  1. Protocol handshake — `initialize` → `initialized` negotiation with a real client over stdio has never been verified. A serialization bug, missing capability, or protocol version mismatch would only surface when a user connects from Cursor/Claude Desktop.

  2. Stdio transport fidelity — The actual JSON-RPC framing over stdin/stdout is never tested. Stray `console.log` calls, buffering issues, or interleaved stderr could break the protocol silently.

  3. Tool execution through the real binary — `sequant_run` spawns `node dist/bin/cli.js run ...` as a child process. Tests mock this spawn entirely. A broken build, missing dist file, or argument serialization bug would pass all current tests.

  4. SSE transport client connection — Integration tests verify HTTP endpoints and rejection logic, but never connect a real `SSEClientTransport` from the SDK and issue tool calls over it.

  5. Resource reads via protocol — `sequant://state` and `sequant://config` are tested via direct handler calls, not through the MCP protocol's `resources/read` method.

  6. Binary resolution in real environment — `resolveCliBinary()` is tested in isolation, but the full chain of the server resolving and spawning the CLI binary is never exercised in a real process tree.

What works well

The existing test suite provides strong coverage for:

  • Tool schema correctness and validation
  • Structured response formatting and size limits
  • Run registry lifecycle and concurrent run tracking
  • SSE multi-client rejection and health endpoint behavior
  • Error handling and edge cases within each tool handler
  • MCP client config detection and generation

These tests should remain unchanged — the E2E layer complements them.

Acceptance Criteria

  • AC-1: Stdio E2E — tool discovery. A test spawns `sequant serve --transport stdio` as a real child process, connects an SDK `Client` via `StdioClientTransport`, calls `listTools()`, and asserts all 3 tools (`sequant_run`, `sequant_status`, `sequant_logs`) are returned with correct schemas.
  • AC-2: Stdio E2E — resource discovery. Same client calls `listResources()` and asserts `sequant://state` and `sequant://config` are present.
  • AC-3: Stdio E2E — tool call round-trip. Client calls `sequant_status` with a non-existent issue number and receives a well-formed MCP response (not a protocol error). This validates the full serialization/deserialization path without needing a real repo setup.
  • AC-4: Stdio E2E — resource read round-trip. Client reads `sequant://config` and receives valid content (may be empty/default if no `.sequant/settings.json` exists, but must not error at the protocol level).
  • AC-5: SSE E2E — client connection and tool call. A test starts `sequant serve --transport sse --port `, connects an SDK `Client` via `SSEClientTransport`, lists tools, and calls `sequant_status`. Validates the full HTTP+SSE protocol path.
  • AC-6: SSE E2E — health endpoint during active connection. While the SSE client is connected, `GET /health` returns `{ "connected": true }`.
  • AC-7: SSE E2E — multi-client rejection. With one SSE client connected, a second `SSEClientTransport` connection attempt receives a 409 status.
  • AC-8: Graceful shutdown. Sending SIGTERM to the server process causes the MCP client to receive a clean disconnect (not a broken pipe or JSON parse error).
  • AC-9: SDK optional guard. Tests skip cleanly when `@modelcontextprotocol/sdk` is not installed, consistent with existing test pattern (issue fix: lazy-load MCP SDK to prevent build failures when SDK is not installed #396).
  • AC-10: No test pollution. E2E tests use temp directories for any state/config files and clean up after themselves. No writes to the real `.sequant/` directory.

Implementation Notes

Test location

`tests/integration/mcp-e2e.integration.test.ts` — follows existing convention.

Client setup pattern

```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

const transport = new StdioClientTransport({
command: "node",
args: ["dist/bin/cli.js", "serve", "--transport", "stdio"],
env: { ...process.env, HOME: tmpDir }, // isolate config
});

const client = new Client({ name: "e2e-test", version: "1.0.0" });
await client.connect(transport);

// ... assertions ...

await client.close();
```

SSE client setup

```typescript
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";

// Start server as child process first
const server = spawn("node", ["dist/bin/cli.js", "serve", "--transport", "sse", "--port", String(port)]);
await waitForHealth(port); // poll GET /health until 200

const transport = new SSEClientTransport(new URL(`http://localhost:\${port}/sse\`));
const client = new Client({ name: "e2e-test-sse", version: "1.0.0" });
await client.connect(transport);
```

Port allocation

Use `getPort()` or bind to port 0 and read back the assigned port to avoid conflicts in CI.

Process cleanup

Follow the pattern from `mcp-serve.integration.test.ts`: detached process groups with `process.kill(-pid, "SIGTERM")` in `afterEach`. See also project memory on process group signals.

Build dependency

E2E tests require `dist/bin/cli.js` to exist. Either:

  • Run `npm run build` in CI before tests
  • Add a `beforeAll` that checks for the built binary and skips with a clear message if missing

Out of Scope

  • Testing `sequant_run` with a real repo and real issue execution (that's a full system test, not E2E for the MCP layer)
  • MCP Inspector integration (useful for manual debugging but not automatable in CI)
  • Cursor/Claude Desktop integration testing (manual verification, not automatable)

Related

Activity

  1. added
    enhancement
    qa
    on Mar 24, 2026
  2. admarble commented on Mar 24, 2026

    @admarble
    ContributorAuthor

    Spec Plan — #414 MCP E2E Tests

    AC Quality Check

    All 10 AC items are clear and testable. Each specifies exact inputs, protocol method, and expected outputs. No vague language detected.

    Scope Assessment

    Metric Value Status
    Feature count 1 (E2E test suite) ✅
    AC items 10 ⚠️ (high count, but all are test cases in one file)
    Directory spread 1 (__tests__/integration/) ✅

    Verdict: ✅ SCOPE_OK — Single test file with related test cases. High AC count is appropriate for comprehensive E2E coverage.

    Non-Goals (from issue)

    • Testing sequant_run with a real repo and real issue execution
    • MCP Inspector integration
    • Cursor/Claude Desktop integration testing

    Acceptance Criteria with Verification

    AC-1: Stdio E2E — tool discovery

    Verification: Integration Test

    • Given: sequant serve --transport stdio spawned as child process
    • When: SDK Client via StdioClientTransport calls listTools()
    • Then: Returns 3 tools (sequant_run, sequant_status, sequant_logs) with correct schemas

    AC-2: Stdio E2E — resource discovery

    Verification: Integration Test

    • Given: Same stdio client connected
    • When: Client calls listResources()
    • Then: Returns sequant://state and sequant://config

    AC-3: Stdio E2E — tool call round-trip

    Verification: Integration Test

    • Given: Stdio client connected
    • When: Client calls sequant_status with non-existent issue number
    • Then: Receives well-formed MCP response (not protocol error), status not_tracked

    AC-4: Stdio E2E — resource read round-trip

    Verification: Integration Test

    • Given: Stdio client connected
    • When: Client reads sequant://config
    • Then: Receives valid content (may be empty/default), no protocol error

    AC-5: SSE E2E — client connection and tool call

    Verification: Integration Test

    • Given: sequant serve --transport sse --port <dynamic> started
    • When: SDK Client via SSEClientTransport connects, lists tools, calls sequant_status
    • Then: Tools listed correctly, sequant_status returns well-formed response

    AC-6: SSE E2E — health endpoint during active connection

    Verification: Integration Test

    • Given: SSE client connected via SDK
    • When: GET /health queried
    • Then: Returns { "connected": true }

    AC-7: SSE E2E — multi-client rejection

    Verification: Integration Test

    • Given: One SSE client connected via SDK
    • When: Second SSEClientTransport attempts connection
    • Then: Receives 409 status

    AC-8: Graceful shutdown

    Verification: Integration Test

    • Given: Server process running with connected client
    • When: SIGTERM sent to server process
    • Then: Client receives clean disconnect (no broken pipe or JSON parse error)

    AC-9: SDK optional guard

    Verification: Integration Test

    AC-10: No test pollution

    Verification: Integration Test

    • Given: Tests use temp directories for state/config
    • When: Tests complete
    • Then: No writes to real .sequant/ directory, temp dirs cleaned up

    Implementation Plan

    Single phase — all work in one file:

    1. Create test file __tests__/integration/mcp-e2e.integration.test.ts

      • Reuse patterns from mcp-serve.integration.test.ts (process spawning, cleanup, port allocation)
      • SDK optional guard using existing skipIf pattern
    2. Stdio E2E describe block (AC-1 through AC-4)

      • Spawn node dist/bin/cli.js serve --transport stdio (or npx tsx bin/cli.ts serve --transport stdio)
      • Connect SDK Client via StdioClientTransport
      • Test tool listing, resource listing, tool call, resource read
      • Isolated HOME env var for config isolation
    3. SSE E2E describe block (AC-5 through AC-7)

      • Spawn SSE server on dynamic port
      • Connect SDK Client via SSEClientTransport
      • Test tool listing + tool call, health endpoint, multi-client rejection
    4. Graceful shutdown test (AC-8)

      • Connect client, send SIGTERM, verify clean disconnect
      • Use detached process group pattern for signal delivery
    5. Test isolation (AC-9, AC-10)

      • SDK guard at top of file
      • Temp dir creation in beforeAll, cleanup in afterAll
      • HOME override to prevent .sequant/ pollution

    Key Decisions

    • Binary path: Use npx tsx bin/cli.ts (source) not node dist/bin/cli.js (compiled) — matches existing integration test pattern and avoids stale build dependency
    • Process groups: Detached spawn + process.kill(-pid) — established pattern
    • Port allocation: net.createServer().listen(0) — established pattern
    • Timeout per test: 15-20s — matches existing tests

    Feature Quality Planning

    Test Coverage Plan:

    • All 10 AC items map to distinct test cases
    • Follows existing integration test patterns exactly
    • Process cleanup in afterEach prevents leaks
    • Temp dir cleanup in afterAll prevents pollution

    Error Handling:

    • SDK optional guard (AC-9)
    • Process cleanup on test failure (afterEach kills all spawned processes)
    • Timeout guards on server startup polling

    Code Quality:

    • Single file, follows existing conventions
    • Reuses utility functions (getAvailablePort, waitForServer, killProcessGroup, spawnServe)
    • No new dependencies needed (SDK already peer dep)

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: Well-defined test-only issue with clear patterns to follow. No UI components.


    Label Review

    Current: enhancement, qa
    Recommended: enhancement, qa (no changes needed)

  3. added a commit that references this issue on Mar 24, 2026
  4. admarble commented on Mar 24, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #414
    Status: READY_FOR_MERGE

    Summary

    • AC: 10/10 met
    • Tests: 8/8 passed (all E2E tests)
    • Build: Passing
    • Full suite: 80/81 files pass (1 pre-existing timeout unrelated to changes)

    Iterations

    • Spec: 1
    • Exec: 1
    • QA: 1 (passed first try)

    Files Changed

    • __tests__/integration/mcp-e2e.integration.test.ts (new, 418 lines)

    PR: #416


    Ready for human review and merge.

  5. added 2 commits that reference this issue on Mar 24, 2026
  6. added 2 commits that reference this issue on Mar 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementqa

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions