From 2eab5c3d4c0f99544711753bd821c7ba6da45f29 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 12:47:59 +0200 Subject: [PATCH 1/8] feat(skills): native skills extension on single-server endpoints (Spec 125 PR-5) /mcp/s/ now speaks io.modelcontextprotocol/skills natively when enable_skills is on and the server is not excluded (T047-T051, #1895): - The instance is built with the extension and the resources capability; aggregated endpoints never announce it (FR-030). - An interceptor inside singleServerSessionGuard answers skills/list, skills/get and resources/read for the server's AVAILABLE skills only, with the upstream's addresses, serving the approved copy byte for byte (FR-029, FR-029a). A policy that would block or change text withholds it instead of rewriting. Each access writes one skill_access row, not-found included. - Transport checks are reused, not copied: the request is first sent through the transport with its method replaced by "ping", and any refusal (missing/foreign/stale session id, unsupported protocol version) is replayed unchanged, so the methods get exactly the refusal tools/call gets. - Endpoint lifecycle (plan D14): instance, transport and generation are acquired together under the cache lock; retirement detaches all three, shuts the transport down (closing open streams) and advances a generation baked into session ids, so an old session is refused. The upstream name is bound to the request, so a retired in-flight initialize still answers with its upstream's instructions. Retired from RefreshSkillsAvailability and lazily on acquisition. Assumption (documented): resources/read is handled by the interceptor rather than an mcp-go resource template, so any upstream scheme works and all three methods share one instrumented path. Verified with the official MCP Inspector 2.16.0 against an isolated core and huggingface.co/mcp: skills/list --verify --require-digests verified 2 approved skills / 5 files, digests equal to the upstream's; held skills not found; /mcp and /mcp/all report the extension unsupported; after switching enable_skills off the old session answers 404 and a new one gets method-not-found. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 1 + ROADMAP.md | 2 +- docs/features/skills.md | 31 +- internal/runtime/skills_agent.go | 8 +- internal/server/mcp.go | 9 + internal/server/mcp_agent_access.go | 2 +- internal/server/mcp_routing.go | 5 + internal/server/mcp_single_server.go | 224 +++++++- .../server/mcp_single_server_session_test.go | 10 +- internal/server/mcp_single_server_test.go | 9 +- internal/server/mcp_skills.go | 1 + internal/server/mcp_skills_test.go | 19 + internal/server/server.go | 51 +- internal/server/skills_native.go | 487 ++++++++++++++++ internal/server/skills_native_test.go | 537 ++++++++++++++++++ specs/125-skills-over-mcp/tasks.md | 10 +- 16 files changed, 1355 insertions(+), 51 deletions(-) create mode 100644 internal/server/skills_native.go create mode 100644 internal/server/skills_native_test.go diff --git a/CLAUDE.md b/CLAUDE.md index b91d4d8f3..4763e2096 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,6 +146,7 @@ tail -f ~/Library/Logs/mcpproxy/main.log # main log (macOS; Linux: ~/.mcpproxy/ - **Windows installer**: [docs/github-actions-windows-wix-research.md](docs/github-actions-windows-wix-research.md). **Prerelease** (`next` branch + `v*-rc.*` tags, opt-in, off stable channels): [docs/prerelease-builds.md](docs/prerelease-builds.md). ## Recent Changes +- 125-skills-over-mcp (PR-5): Go 1.26, backend + docs — native skills extension on `/mcp/s/` only (`internal/server/skills_native.go`): with `enable_skills` on and the server not excluded the instance is built with `WithExtensions`+`WithResourceCapabilities`; an interceptor (inside `singleServerSessionGuard`, in front of the transport) answers `skills/list`, `skills/get`, `resources/read` from `ListAvailableSkills`/`AvailableSkillFile`, byte for byte (a mutating output policy withholds instead of rewriting), one `skill_access` row each (tool = method). Transport checks are reused, not copied: the request is first sent through the transport with its method replaced by `ping`, and a refusal is replayed unchanged. Endpoint lifecycle (`mcp_single_server.go`): instance, transport and generation acquired together under `singleServersMu` (`acquireSingleServerEndpoint`), retirement detaches all three and advances the generation baked into session ids (`newSingleServerSessionIDs(server, gen)`), retired GET streams end, the upstream name rides on the request (`withSingleServerEndpoint`, `singleServerNameFor(ctx, srv)`); retired from `RefreshSkillsAvailability` and lazily on acquisition. Docs: `docs/features/skills.md` "Native skills on single-server endpoints". **No new dependencies.** - 126-day-two-activation (PR-A): Go 1.26, backend + docs — telemetry schema 17, instrumentation only (no onboarding, UI or API change). Install anchor: `storage.EnsureInstallAnchor` (own bucket `install_anchor`, written once in `runtime.New` after the Spec 080 shutdown marker and Spec 123 OAuth boot sweep, before any other startup write, only when `config.db` held no record other than `meta/schema_version` at open, `BoltDB.WasEmptyAtOpen`; never from onboarding writes; recorded with telemetry off; read once per process for both `day_two` and `window_age`). `upstream_outcomes {succeeded, unusable, succeeded_non_starter, coverage, window_age}` (`internal/telemetry/upstream_outcomes.go`): one outcome per LOGICAL call that dispatched (dispatch counts requests), begun right after `noteUpstreamDispatched` and deferred (`upstreamOutcome` in `internal/server/mcp_upstream_telemetry.go`) on the wrapper, direct routing and `code_execution` sub-calls, guarded by an AST test; part of the drained window (retries byte-identical); `coverage` from the persisted `outcome_window_undelivered` marker (`outcome_window.go`: set by the first outcome after start or a Drain, cleared after a 2xx only if nothing was counted since that drain, both under the outcome window's own mutex, never `deliveryMu`), `window_age` = install age when the window opened (start or Drain), `install_origin: fresh` personal only. `day_two {install_origin, install_age, success_scope_ever}` personal only (`day_two.go`: UTC calendar-date buckets; `success_scope.go` forward-only ordinal in the activation bucket). `runtime.StarterClassifier` (default false, `SetStarterClassifier` for PR-B) + `Runtime.RecordUpstreamOutcome`. `ScanForPII` closed-object rule `day_two_field_invalid`. Docs: `docs/features/telemetry.md` "Schema v17". **No new dependencies.** - 125-skills-over-mcp (PR-3): Go 1.26, backend + CLI + docs — approved skills reach agents through three read-only built-ins, registered only while `enable_skills` is on (`MCPProxyServer.RefreshSkillsAvailability`: default registry, call-tool, code-execution and direct surfaces; never `/mcp/s/`, never from `code_execution`): `retrieve_skills(query, limit)`, `load_skill(id, offset, limit, version)`, `read_skill_file(id, path, offset, limit, version)` (`internal/server/mcp_skills.go`). Everything comes from the approved copy through `Runtime.AvailableSkill` / `AvailableSkillFile` / `SearchAvailableSkills` (`internal/runtime/skills_agent.go`); one refusal `skill not found: ` for every unavailable reason; reach = `resolveActiveProfileWithSource` → `serverInScope`, tool policy not applied. Search: memory-only Bleve in `internal/skills/index`, one index per reach, every match re-checked against its record. Paging: parts of ≤60,000 bytes with `Version:` in the header. Output policy (`mcp_skills_output.go`): block/redact/strip on the whole file before paging, also on names, descriptions and file names; skills build a detector when a policy is switched on after start. Activity type `skill_access` (administrator-only, like `skill_quarantine_change`). Scoped REST: `GET /api/v1/servers/{id}/skills{,/content}` answer an agent token with available skills from the approved copy through the same policy. Records of skills a listing did not name are bounded (200 per server). Docs: `docs/features/skills.md` "Skills for agents". **No new dependencies.** - 125-skills-over-mcp (PR-2): Go 1.26, backend + CLI + docs — the skills approval gate, still administrator-only and offered to no agent. `decideSkill` (`internal/runtime/skills_quarantine.go`) is the whole status rule: `manual` holds new and changed skills, `scan` approves a new skill only on a clean and complete scan and always holds a changed one, `auto` / `quarantine_enabled:false` approve; a hash equal to the approved one restores approved; `Blocked` survives everything. Scan (`skills_scan.go`): every text file in ≤48 KiB chunks through `ScanToolMetadataVerdict`, after the reads and outside the upstream timeout, 45 s per refresh with follow-up refreshes, 1 MiB and 2 min per skill (`size_cap` / `time_limit` are kept, `coverage` is retried), result bound to the content hash. Review-bound decisions (`skills_approval.go`): `ApproveSkillsReviewedAt` (expected hash per skill + incarnation, whole request refused with nothing written) and `SetSkillsBlockedAt`, records-only writes (`storage.UpdateSkillApprovals`). REST `POST /api/v1/servers/{id}/skills/approve|block|unblock` (409 `review_out_of_date` / `server_replaced`, 422 `skill_unusable`), CLI `mcpproxy skills approve|block|unblock`, `skills show --diff`. Activity type `skill_quarantine_change` is administrator-only on every activity read door and on SSE (`storage.IsAdminOnlyActivityType`). Docs: `docs/features/skills.md` "Reviewing skills". **No new dependencies.** diff --git a/ROADMAP.md b/ROADMAP.md index ba7080e52..616504563 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1207,4 +1207,4 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [122-scanner-skillspector-checks](./specs/122-scanner-skillspector-checks/) | `shipped` | 31/31 (100%) | | [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | `drafted` | 0/56 (0%) | | [124-session-failure-timeline](./specs/124-session-failure-timeline/) | `drafted` | 0/74 (0%) | -| [125-skills-over-mcp](./specs/125-skills-over-mcp/) | `in-flight` | 41/51 (80%) | +| [125-skills-over-mcp](./specs/125-skills-over-mcp/) | `in-flight` | 46/51 (90%) | diff --git a/docs/features/skills.md b/docs/features/skills.md index 64b71c2bb..909d0d2a5 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -222,7 +222,7 @@ Call the tool again with that `offset` and `version`. The header is repeated on ### Where the tools are offered -On every MCP endpoint that offers `retrieve_tools`, and on the direct endpoint (`/mcp/all`) next to `describe_tool`. They are not offered on single-server endpoints (`/mcp/s/`), and a `code_execution` script cannot call them. Turning `enable_skills` on or off adds or removes the tools at once and tells connected clients that the tool list changed. With the switch off, the tool list is the same as in a build without this feature. +On every MCP endpoint that offers `retrieve_tools`, and on the direct endpoint (`/mcp/all`) next to `describe_tool`. They are not offered on single-server endpoints (`/mcp/s/`), which serve skills natively instead (see [Native skills on single-server endpoints](#native-skills)), and a `code_execution` script cannot call them. Turning `enable_skills` on or off adds or removes the tools at once and tells connected clients that the tool list changed. With the switch off, the tool list is the same as in a build without this feature. ### Activity @@ -234,6 +234,31 @@ mcpproxy activity list --type skill_access While the tools are offered, the instructions MCPProxy sends to every client name them, and `mcpproxy agent-instructions` adds a skills line to its snippet; see [Agent Instructions](agent-instructions.md). +## Native skills on single-server endpoints {#native-skills} + +A client that implements the skills extension itself (for example the MCP Inspector, `--method skills/list --verify`) can connect to the single-server endpoint of one upstream, `http://127.0.0.1:8080/mcp/s/`, and use its own skills interface and consent prompts. With `enable_skills` on and the server not excluded (`expose_skills: false`), that endpoint: + +- announces the extension (`capabilities.extensions["io.modelcontextprotocol/skills"]`) and the `resources` capability it requires; +- answers `skills/list` with exactly the skills of that server that are available to agents, under the addresses the upstream uses (`skill://…`), with the frontmatter, digest and size of the approved copy. Only text files are listed: binary files are not served in this version. The whole listing is one page; +- answers `skills/get` for one of those addresses, and `resources/read` for one of their files. + +What a client reads is the approved copy, byte for byte. The client checks the digests itself, so MCPProxy adds no header and rewrites nothing: when the output sanitisation policy would block or change a file, the read is refused (`skill output blocked by the output sanitisation policy`), and a skill whose address, file addresses or frontmatter the policy would change is left out of the listing. Sensitive-data detection still runs on every file read and records its findings without changing the bytes. + +A held, changed, blocked or unusable skill is not listed, and asking for it by address answers `skill not found: ` (`skills/get`) or `resource not found: ` (`resources/read`), error code `-32002`, the same answer as for an address that does not exist. + +The aggregated endpoints (`/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/`) never announce the extension. They offer the [skill tools](#agent-tools) instead. + +**Same door as the tools.** A caller whose credential or profile does not reach the server gets the endpoint's `404`, exactly as for its tools. Each of the three requests is answered only after the endpoint's transport has accepted it the way it accepts a `tools/call`: a request without a session id, with a session id another endpoint issued, or with a protocol version the endpoint does not serve gets the same refusal a `tools/call` gets. + +**Following the switch.** Turning `enable_skills` on or off, or changing a server's `expose_skills`, retires that server's single-server endpoint: its open streams are closed and the session ids it issued are refused (`404`), so the client initializes again and sees the new capabilities. Nothing has to be restarted. + +**Activity.** Every native listing, entry and file read is a `skill_access` row with the method in the tool column (`skills/list`, `skills/get`, `resources/read`), the action (`list`, `load`, `read`), the outcome (`not_found` included) and the caller's session. + +```bash +npx @modelcontextprotocol/inspector --cli http://127.0.0.1:8080/mcp/s/hf --transport http \ + --method skills/list --verify --require-digests +``` + ## Command line All commands need a running core (`mcpproxy serve`) and administrator credentials. They support `-o json` and `-o yaml`. `approve`, `block` and `unblock` are described under [Reviewing skills](#reviewing-skills). @@ -316,7 +341,9 @@ Approve, block, unblock and refresh require administrator credentials (the API k **An agent gets `skill not found` for a skill I can see.** The skill is not available to that agent. Check, in this order: `mcpproxy skills list --server ` shows it `approved`, not blocked and `listed`; the server is enabled, not quarantined and has no `expose_skills: false`; the agent's token or profile includes the server. `mcpproxy activity list --type skill_access` shows the call and its outcome. -**An agent does not see the skill tools.** `enable_skills` is off, or the client is connected to a single-server endpoint (`/mcp/s/`), where they are not offered. +**An agent does not see the skill tools.** `enable_skills` is off, or the client is connected to a single-server endpoint (`/mcp/s/`), where they are not offered: a client that speaks the skills extension gets the server's skills natively there. + +**A native client says the server does not declare the skills extension.** It is connected to an aggregated endpoint, `enable_skills` is off, or the server has `expose_skills: false`. Connect it to `/mcp/s/`. After changing either switch, the client must initialize again (its old session id answers `404`). **A skill I approved shows `changed`.** The server changed its content. Compare with `mcpproxy skills show : --diff` and approve again if the change is fine. Agents keep being refused until then. diff --git a/internal/runtime/skills_agent.go b/internal/runtime/skills_agent.go index b26fb02d3..034b32a2d 100644 --- a/internal/runtime/skills_agent.go +++ b/internal/runtime/skills_agent.go @@ -35,8 +35,11 @@ type AvailableSkill struct { Name string Description string ApprovedHash string - Files []storage.SkillFile - TotalSize int64 + // Frontmatter is the approved copy's frontmatter as stored (JSON), for the + // native listing on /mcp/s/ (Spec 125 FR-029). + Frontmatter json.RawMessage + Files []storage.SkillFile + TotalSize int64 } // publishSkillsChanged announces a change of a server's skills and moves the @@ -88,6 +91,7 @@ func availableSkillOf(serverName string, rec *storage.SkillApprovalRecord) *Avai Name: name, Description: desc, ApprovedHash: rec.ApprovedHash, + Frontmatter: append(json.RawMessage(nil), rec.Approved.Frontmatter...), Files: append([]storage.SkillFile(nil), rec.Approved.Files...), } for _, f := range a.Files { diff --git a/internal/server/mcp.go b/internal/server/mcp.go index 0c77e784f..8e5fb62bc 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -297,9 +297,18 @@ type MCPProxyServer struct { // own names. They are projections of the published direct catalog and are // re-registered under directRefreshMu, after the direct surface. The lock // order is directRefreshMu, then singleServersMu. + // + // singleServersMu is also each endpoint's lifecycle lock (Spec 125 D14): a + // request takes the instance, its transport and the endpoint generation + // together under it, and a retirement detaches all three under it. It is + // never held across serving a request or shutting a transport down. singleServerOpts []mcpserver.ServerOption singleServersMu sync.Mutex singleServers map[string]*singleServerSurface + // singleServerGens is each endpoint's generation. It only grows within a + // process; a retirement advances it, so the session ids it issued earlier + // are refused. + singleServerGens map[string]uint64 // directRefreshMu serializes whole rebuilds so SetTools and the matching // publishDirectCatalog cannot interleave with another rebuild's pair. diff --git a/internal/server/mcp_agent_access.go b/internal/server/mcp_agent_access.go index d54f92460..6f6ac9d2b 100644 --- a/internal/server/mcp_agent_access.go +++ b/internal/server/mcp_agent_access.go @@ -327,7 +327,7 @@ func (p *MCPProxyServer) instructionsForCaller(ctx context.Context, srv *mcpserv // A single-server surface (/mcp/s/) stands in for the upstream // server itself, so it answers with that server's own instructions and // nothing of mcpproxy's. - if name, ok := p.singleServerNameFor(srv); ok { + if name, ok := p.singleServerNameFor(ctx, srv); ok { if !p.singleServerAdmits(ctx, name) { return "" } diff --git a/internal/server/mcp_routing.go b/internal/server/mcp_routing.go index 451f21360..a81bd5807 100644 --- a/internal/server/mcp_routing.go +++ b/internal/server/mcp_routing.go @@ -1842,6 +1842,11 @@ func (p *MCPProxyServer) RefreshSkillsAvailability() { } p.directRefreshMu.Unlock() } + + // Spec 125 D14: a single-server instance's capabilities are fixed when it + // is built, so an endpoint whose native skills surface no longer matches + // the switch is retired and rebuilt on its next request. + p.retireStaleNativeSurfaces() } // buildAggregatedServerPrompts combines built-in prompts with upstream diff --git a/internal/server/mcp_single_server.go b/internal/server/mcp_single_server.go index 4b6fadd4c..e5eb0ea0d 100644 --- a/internal/server/mcp_single_server.go +++ b/internal/server/mcp_single_server.go @@ -8,6 +8,7 @@ import ( "fmt" "net/http" "strings" + "time" "github.com/google/uuid" "github.com/mark3labs/mcp-go/mcp" @@ -47,23 +48,79 @@ type singleServerSurface struct { // stay byte-identical while it moves, and the stamp and handler close over // it, so a re-registration is skipped only when BOTH fingerprints match. routingFP string + + // Spec 125 D14. native: the instance was built with the skills extension + // and resource capabilities (both are fixed when an instance is built). + // gen: the endpoint generation the instance belongs to. transport: its + // Streamable HTTP transport, created on first request under the lifecycle + // lock. retired is closed when the endpoint is retired. + native bool + gen uint64 + transport *mcpserver.StreamableHTTPServer + retired chan struct{} +} + +// singleServerEndpoint is what one request on /mcp/s/ uses, taken as +// one value under the lifecycle lock: nothing in it is looked up again while +// the request runs. +type singleServerEndpoint struct { + name string + server *mcpserver.MCPServer + transport *mcpserver.StreamableHTTPServer + gen uint64 + native bool + retired <-chan struct{} +} + +type singleServerEndpointKey struct{} + +// withSingleServerEndpoint binds the acquired endpoint to the request, so +// everything that serves it (the instructions hook included) knows which +// upstream the instance stands in for without asking the live cache. +func withSingleServerEndpoint(ctx context.Context, ep *singleServerEndpoint) context.Context { + return context.WithValue(ctx, singleServerEndpointKey{}, ep) +} + +func singleServerEndpointFrom(ctx context.Context) *singleServerEndpoint { + ep, _ := ctx.Value(singleServerEndpointKey{}).(*singleServerEndpoint) + return ep } // SingleServerMCP returns the MCP server for /mcp/s/, creating it on // first use, or nil when no upstream server with that name is configured. -// The returned server is stable for the life of the process: later catalog -// rebuilds re-register its tools in place. +// The instance is kept until its endpoint is retired (the native skills +// surface switched on or off, Spec 125 D14); catalog rebuilds re-register its +// tools in place. func (p *MCPProxyServer) SingleServerMCP(name string) *mcpserver.MCPServer { if name == "" || p.singleServerOpts == nil || !p.upstreamConfigured(name) { return nil } + s := p.singleServerSurfaceFor(name) + if s == nil { + return nil + } + return s.server +} + +// singleServerSurfaceFor returns the live surface of name, building it (with +// the native surface when it should have one) when there is none. A surface +// whose native surface no longer matches the live configuration is retired +// first, so the switch is followed even when no reload event reached +// RefreshSkillsAvailability. +func (p *MCPProxyServer) singleServerSurfaceFor(name string) *singleServerSurface { + wantNative := p.singleServerWantsNative(name) + var stale *mcpserver.StreamableHTTPServer p.singleServersMu.Lock() if s, ok := p.singleServers[name]; ok { - p.singleServersMu.Unlock() - return s.server + if s.native == wantNative { + p.singleServersMu.Unlock() + return s + } + stale = p.retireSingleServerLocked(name) } p.singleServersMu.Unlock() + shutdownSingleServerTransport(stale) // Lock order: directRefreshMu, then singleServersMu (the rebuild path // holds the first and takes the second). Holding directRefreshMu while @@ -75,18 +132,130 @@ func (p *MCPProxyServer) SingleServerMCP(name string) *mcpserver.MCPServer { defer p.singleServersMu.Unlock() if s, ok := p.singleServers[name]; ok { - return s.server + return s + } + opts := p.singleServerOpts + if wantNative { + opts = append(append([]mcpserver.ServerOption(nil), opts...), nativeSkillsServerOptions()...) } s := &singleServerSurface{ - name: name, - server: mcpserver.NewMCPServer("mcpproxy-go", mcpServerVersion(), p.singleServerOpts...), + name: name, + server: mcpserver.NewMCPServer("mcpproxy-go", mcpServerVersion(), opts...), + native: wantNative, + gen: p.singleServerGens[name], + retired: make(chan struct{}), } if p.singleServers == nil { p.singleServers = map[string]*singleServerSurface{} } p.singleServers[name] = s p.registerSingleServerTools(s, p.loadDirectCatalog()) - return s.server + return s +} + +// acquireSingleServerEndpoint returns the endpoint a request on /mcp/s/ +// is served by: instance, transport and generation together, taken under the +// lifecycle lock. newTransport builds the transport the first time the +// instance is served. ok is false when no such server is configured. +func (p *MCPProxyServer) acquireSingleServerEndpoint(name string, newTransport func(srv *mcpserver.MCPServer, gen uint64) *mcpserver.StreamableHTTPServer) (*singleServerEndpoint, bool) { + if name == "" || p.singleServerOpts == nil || !p.upstreamConfigured(name) { + return nil, false + } + // A retirement can land between building the surface and taking it below; + // then the next attempt builds the replacement. Two attempts are enough + // unless the switch flips again in between, which a third covers. + for attempt := 0; attempt < 3; attempt++ { + s := p.singleServerSurfaceFor(name) + if s == nil { + return nil, false + } + p.singleServersMu.Lock() + if cur, ok := p.singleServers[name]; !ok || cur != s { + p.singleServersMu.Unlock() + continue + } + if s.transport == nil { + s.transport = newTransport(s.server, s.gen) + } + ep := &singleServerEndpoint{ + name: name, server: s.server, transport: s.transport, + gen: s.gen, native: s.native, retired: s.retired, + } + p.singleServersMu.Unlock() + return ep, true + } + return nil, false +} + +// retireSingleServerLocked detaches the endpoint of name in one step: the +// instance leaves the cache, its transport is returned for the caller to shut +// down after releasing the lock, and the generation advances so a session id +// issued before is refused. The caller holds singleServersMu. +func (p *MCPProxyServer) retireSingleServerLocked(name string) *mcpserver.StreamableHTTPServer { + s, ok := p.singleServers[name] + if !ok { + return nil + } + delete(p.singleServers, name) + if p.singleServerGens == nil { + p.singleServerGens = map[string]uint64{} + } + if next := s.gen + 1; next > p.singleServerGens[name] { + p.singleServerGens[name] = next + } + close(s.retired) + return s.transport +} + +// shutdownSingleServerTransport closes a detached transport's open streams. +// The transport is used as an http.Handler, so Shutdown stops no listener; it +// closes the sessions it holds. +func shutdownSingleServerTransport(t *mcpserver.StreamableHTTPServer) { + if t == nil { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = t.Shutdown(ctx) +} + +// retireStaleNativeSurfaces retires every cached single-server endpoint whose +// native skills surface differs from what the live configuration asks for +// (Spec 125 D14, "Following the switch"). The next request builds a fresh +// instance and transport. +func (p *MCPProxyServer) retireStaleNativeSurfaces() { + p.singleServersMu.Lock() + names := make([]string, 0, len(p.singleServers)) + for name := range p.singleServers { + names = append(names, name) + } + p.singleServersMu.Unlock() + + for _, name := range names { + want := p.singleServerWantsNative(name) + p.singleServersMu.Lock() + var stale *mcpserver.StreamableHTTPServer + if s, ok := p.singleServers[name]; ok && s.native != want { + stale = p.retireSingleServerLocked(name) + p.logger.Info("retired single-server endpoint: native skills surface changed", + zap.String("server", name), zap.Bool("native", want)) + } + p.singleServersMu.Unlock() + shutdownSingleServerTransport(stale) + } +} + +// singleServerTransportCount is how many single-server transports are held. +func (p *MCPProxyServer) singleServerTransportCount() int { + p.singleServersMu.Lock() + defer p.singleServersMu.Unlock() + n := 0 + for _, s := range p.singleServers { + if s.transport != nil { + n++ + } + } + return n } // refreshSingleServerSurfacesLocked re-registers every existing single-server @@ -191,11 +360,18 @@ func singleServerRoutingFingerprint(name string, cat *directCatalog) string { } // singleServerNameFor reports whether srv is a single-server surface and, if -// so, which upstream it stands in for. -func (p *MCPProxyServer) singleServerNameFor(srv *mcpserver.MCPServer) (string, bool) { +// so, which upstream it stands in for. A request served on /mcp/s/ +// carries its endpoint, bound when it was acquired, and that binding answers: +// an instance retired while the request runs is no longer in the cache, and +// must still answer as the upstream it was built for. Without a binding (a +// call from outside the HTTP route) the cache is asked. +func (p *MCPProxyServer) singleServerNameFor(ctx context.Context, srv *mcpserver.MCPServer) (string, bool) { if srv == nil { return "", false } + if ep := singleServerEndpointFrom(ctx); ep != nil && ep.server == srv { + return ep.name, true + } p.singleServersMu.Lock() defer p.singleServersMu.Unlock() for name, s := range p.singleServers { @@ -317,17 +493,25 @@ func describeConfinedServer(ctx context.Context) (string, bool) { // /mcp/s/ surface. mcp-go's default manager accepts any well-formed // "mcp-session-", so a session id minted on one surface (and the client // identity attributed to it) would be accepted on every other. Each surface's -// ids carry a tag derived from its server name, and a surface accepts only its -// own. Like the default manager it tracks nothing, so ids stay valid across a -// restart of the same surface. +// ids carry a tag derived from its server name and its endpoint generation, +// and a surface accepts only its own. Like the default manager it tracks +// nothing, so ids stay valid across a restart of the same surface; a +// retirement (Spec 125 D14) advances the generation, so ids issued before it +// are refused and the client initializes again. type singleServerSessionIDs struct { suffix string } const singleServerSessionPrefix = "mcp-session-" -func newSingleServerSessionIDs(server string) *singleServerSessionIDs { - sum := sha256.Sum256([]byte("mcpproxy/single-server-session/" + server)) +// newSingleServerSessionIDs returns the ids of one endpoint generation. +// Generation 0 keeps the tag ids had before generations existed. +func newSingleServerSessionIDs(server string, gen uint64) *singleServerSessionIDs { + seed := "mcpproxy/single-server-session/" + server + if gen > 0 { + seed += fmt.Sprintf("/gen/%d", gen) + } + sum := sha256.Sum256([]byte(seed)) return &singleServerSessionIDs{suffix: "." + hex.EncodeToString(sum[:8])} } @@ -359,8 +543,8 @@ func (m *singleServerSessionIDs) Terminate(string) (isNotAllowed bool, err error // on POST: its GET (the legacy standalone stream) and DELETE accept any id and // would register or close the session record another endpoint's session owns. // Unknown-session is a 404, as the transport answers for a terminated one. -func singleServerSessionGuard(server string, next http.Handler) http.Handler { - ids := newSingleServerSessionIDs(server) +func singleServerSessionGuard(server string, gen uint64, next http.Handler) http.Handler { + ids := newSingleServerSessionIDs(server, gen) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if sid := r.Header.Get("Mcp-Session-Id"); sid != "" { if _, err := ids.Validate(sid); err != nil { @@ -374,10 +558,10 @@ func singleServerSessionGuard(server string, next http.Handler) http.Handler { // singleServerStreamableOptions is the Streamable HTTP option set of a // /mcp/s/ transport: the shared client-facing options plus session ids -// bound to that server. -func singleServerStreamableOptions(cfgProvider func() *config.Config, server string) []mcpserver.StreamableHTTPOption { +// bound to that server and endpoint generation. +func singleServerStreamableOptions(cfgProvider func() *config.Config, server string, gen uint64) []mcpserver.StreamableHTTPOption { return append(clientFacingStreamableOptions(cfgProvider), - mcpserver.WithSessionIdManager(newSingleServerSessionIDs(server))) + mcpserver.WithSessionIdManager(newSingleServerSessionIDs(server, gen))) } // singleServerDescribeTool is describe_tool with its tool_ids description diff --git a/internal/server/mcp_single_server_session_test.go b/internal/server/mcp_single_server_session_test.go index ee3ecb9a0..9a67b5374 100644 --- a/internal/server/mcp_single_server_session_test.go +++ b/internal/server/mcp_single_server_session_test.go @@ -22,7 +22,7 @@ import ( // (and the client identity attributed to it) cannot be carried across // single-server surfaces. func TestSingleServerSessionIDs_BoundToTheirServer(t *testing.T) { - a, b := newSingleServerSessionIDs("alpha"), newSingleServerSessionIDs("beta") + a, b := newSingleServerSessionIDs("alpha", 0), newSingleServerSessionIDs("beta", 0) id := a.Generate() _, err := a.Validate(id) require.NoError(t, err) @@ -41,7 +41,7 @@ func TestSingleServerStreamable_RefusesAnotherServersSession(t *testing.T) { srv.AddTool(mcp.NewTool("echo"), func(_ context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) { return mcp.NewToolResultText("ok"), nil }) - return httptest.NewServer(mcpserver.NewStreamableHTTPServer(srv, singleServerStreamableOptions(nil, name)...)) + return httptest.NewServer(mcpserver.NewStreamableHTTPServer(srv, singleServerStreamableOptions(nil, name, 0)...)) } alpha, beta := newSurface("alpha"), newSurface("beta") defer alpha.Close() @@ -113,7 +113,7 @@ func TestStripServerPrefixInJSON_DidYouMeanKeepsOnlyThisServer(t *testing.T) { // another endpoint's session record cannot be registered or closed here. func TestSingleServerSessionGuard_RefusesForeignIDOnEveryMethod(t *testing.T) { var reached int - guarded := httptest.NewServer(singleServerSessionGuard("beta", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + guarded := httptest.NewServer(singleServerSessionGuard("beta", 0, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { reached++ w.WriteHeader(http.StatusNoContent) }))) @@ -129,14 +129,14 @@ func TestSingleServerSessionGuard_RefusesForeignIDOnEveryMethod(t *testing.T) { resp.Body.Close() return resp.StatusCode } - foreign := newSingleServerSessionIDs("alpha").Generate() + foreign := newSingleServerSessionIDs("alpha", 0).Generate() for _, m := range []string{http.MethodGet, http.MethodDelete, http.MethodPost} { assert.Equal(t, http.StatusNotFound, do(m, foreign), "%s with alpha's session on beta", m) assert.Equal(t, http.StatusNotFound, do(m, "mcp-session-980d2b73-e933-46a0-8d2f-0b9090f6bb79"), "%s with an untagged id", m) } assert.Zero(t, reached, "a refused request never reaches the transport") - own := newSingleServerSessionIDs("beta").Generate() + own := newSingleServerSessionIDs("beta", 0).Generate() assert.Equal(t, http.StatusNoContent, do(http.MethodGet, own)) assert.Equal(t, http.StatusNoContent, do(http.MethodDelete, own)) assert.Equal(t, http.StatusNoContent, do(http.MethodPost, ""), "initialize carries no session id") diff --git a/internal/server/mcp_single_server_test.go b/internal/server/mcp_single_server_test.go index dce501337..83e90809d 100644 --- a/internal/server/mcp_single_server_test.go +++ b/internal/server/mcp_single_server_test.go @@ -23,8 +23,9 @@ func newSingleServerSurfaceForTest(t *testing.T, p *MCPProxyServer, name string) t.Helper() require.NotNil(t, p.singleServerOpts, "initRoutingModeServers must prepare the single-server options") s := &singleServerSurface{ - name: name, - server: mcpserver.NewMCPServer("mcpproxy-go", mcpServerVersion(), p.singleServerOpts...), + name: name, + server: mcpserver.NewMCPServer("mcpproxy-go", mcpServerVersion(), p.singleServerOpts...), + retired: make(chan struct{}), } p.directRefreshMu.Lock() defer p.directRefreshMu.Unlock() @@ -191,11 +192,11 @@ func TestSingleServerNameFor(t *testing.T) { p := newDirectDescribeProxy(t) s := newSingleServerSurfaceForTest(t, p, "github") - name, ok := p.singleServerNameFor(s.server) + name, ok := p.singleServerNameFor(context.Background(), s.server) assert.True(t, ok) assert.Equal(t, "github", name) - _, ok = p.singleServerNameFor(p.directServer) + _, ok = p.singleServerNameFor(context.Background(), p.directServer) assert.False(t, ok, "the direct server is not a single-server surface") } diff --git a/internal/server/mcp_skills.go b/internal/server/mcp_skills.go index 8e9509293..fa5d6e696 100644 --- a/internal/server/mcp_skills.go +++ b/internal/server/mcp_skills.go @@ -70,6 +70,7 @@ const ( // it behind this interface so every handler test runs without the real catalog. type skillsCatalog interface { AvailableSkill(serverName, skillPath string) (*runtime.AvailableSkill, error) + ListAvailableSkills(serverName string) ([]*runtime.AvailableSkill, error) AvailableSkillFile(serverName, skillPath, relPath string) ([]byte, storage.SkillFile, *runtime.AvailableSkill, error) SearchAvailableSkills(query string, limit int, reach runtime.SkillReach) ([]runtime.AvailableSkill, int, error) } diff --git a/internal/server/mcp_skills_test.go b/internal/server/mcp_skills_test.go index bf84d4f50..e176eb509 100644 --- a/internal/server/mcp_skills_test.go +++ b/internal/server/mcp_skills_test.go @@ -83,6 +83,25 @@ func (f *fakeSkillsCatalog) AvailableSkill(server, path string) (*runtime.Availa return &cp, nil } +func (f *fakeSkillsCatalog) ListAvailableSkills(server string) ([]*runtime.AvailableSkill, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls++ + var all []runtime.AvailableSkill + for _, sk := range f.skills { + if sk.available && sk.skill.Server == server { + all = append(all, sk.skill) + } + } + sortSkills(all) + out := make([]*runtime.AvailableSkill, len(all)) + for i := range all { + cp := all[i] + out[i] = &cp + } + return out, nil +} + func (f *fakeSkillsCatalog) AvailableSkillFile(server, path, rel string) ([]byte, storage.SkillFile, *runtime.AvailableSkill, error) { f.mu.Lock() defer f.mu.Unlock() diff --git a/internal/server/server.go b/internal/server/server.go index 4dd7af8c0..341b55e09 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -110,9 +110,9 @@ func (s *Server) setSecurityScanner(svc securityScannerService) { type Server struct { logger *zap.Logger runtime *runtime.Runtime - // singleServerHTTP maps each /mcp/s/ MCP server to its Streamable - // HTTP transport, created on first use (serveSingleServer). - singleServerHTTP sync.Map // *server.MCPServer -> *server.StreamableHTTPServer + // singleServerAcquired, when set (tests only), runs after a /mcp/s/ + // request has acquired its endpoint and before it is served. + singleServerAcquired atomic.Pointer[func(name string)] // bundleDegradedLogged is the last degraded-coverage reason already logged // by bundleAdmissionSuspended (Spec 101 FR-007), so the suspension is // logged once per reason rather than once per settle event. @@ -5816,24 +5816,53 @@ func (s *Server) ServerIncarnation(serverName string) (int64, bool) { // serveSingleServer serves /mcp/s/. An unknown server, or one the // caller's credential may not use, gets the same 404, so the route cannot be // used to probe which servers exist. +// +// The endpoint (instance, transport, generation) is acquired as one value and +// nothing about it is looked up again while the request runs, so a retirement +// in the meantime (Spec 125 D14) cannot pair this request with a newer +// instance. The handler chain is: session guard (this endpoint and +// generation) -> native skills interceptor (when the instance has the native +// surface) -> the instance's transport. func (s *Server) serveSingleServer(w http.ResponseWriter, r *http.Request) { name := strings.TrimPrefix(r.URL.Path, "/mcp/s/") name = strings.TrimSuffix(name, "/") if i := strings.Index(name, "/"); i >= 0 { name = name[:i] } - var srv *server.MCPServer + var ( + ep *singleServerEndpoint + ok bool + ) if s.mcpProxy != nil && s.mcpProxy.singleServerAdmits(r.Context(), name) { - srv = s.mcpProxy.SingleServerMCP(name) + ep, ok = s.mcpProxy.acquireSingleServerEndpoint(name, func(srv *server.MCPServer, gen uint64) *server.StreamableHTTPServer { + return server.NewStreamableHTTPServer(srv, singleServerStreamableOptions(s.liveConfig, name, gen)...) + }) } - if srv == nil { + if !ok { http.Error(w, `{"error":"Server not found"}`, http.StatusNotFound) return } - transport, ok := s.singleServerHTTP.Load(srv) - if !ok { - transport, _ = s.singleServerHTTP.LoadOrStore(srv, - server.NewStreamableHTTPServer(srv, singleServerStreamableOptions(s.liveConfig, name)...)) + if hook := s.singleServerAcquired.Load(); hook != nil { + (*hook)(name) + } + ctx := withSingleServerEndpoint(r.Context(), ep) + if r.Method == http.MethodGet { + // A stream opened on an endpoint that is retired while it is open (or + // just before it registered) ends with the retirement. + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + defer cancel() + go func() { + select { + case <-ep.retired: + cancel() + case <-ctx.Done(): + } + }() + } + var next http.Handler = ep.transport + if ep.native { + next = s.mcpProxy.nativeSkillsInterceptor(ep, next) } - singleServerSessionGuard(name, transport.(*server.StreamableHTTPServer)).ServeHTTP(w, r) + singleServerSessionGuard(name, ep.gen, next).ServeHTTP(w, r.WithContext(ctx)) } diff --git a/internal/server/skills_native.go b/internal/server/skills_native.go new file mode 100644 index 000000000..ce9fbccc0 --- /dev/null +++ b/internal/server/skills_native.go @@ -0,0 +1,487 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "strings" + "time" + + "github.com/mark3labs/mcp-go/mcp" + mcpserver "github.com/mark3labs/mcp-go/server" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/skills" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/telemetry" +) + +// Spec 125 PR-5 (plan D14, FR-029, FR-029a, FR-030): the skills extension, +// natively, on /mcp/s/ only. +// +// A client that speaks io.modelcontextprotocol/skills connects to the +// single-server endpoint of one upstream and is told the extension is there. +// It lists that server's AVAILABLE skills with the addresses the upstream +// uses, gets one entry, and reads files with resources/read. Everything comes +// from the approved copy, byte for byte: the client verifies the digests +// itself, so nothing is rewritten and no header is added. What the output +// policy would change is withheld instead of being served changed. +// +// mcp-go has no hook for a method it does not know, so the three methods are +// answered by an interceptor in front of the instance's transport. Before it +// answers, the request must pass every check the transport applies to a +// tools/call: the interceptor sends the same request, with its method +// replaced by "ping", through the transport itself and answers only when the +// transport accepted it. A refusal (wrong content type, missing, foreign or +// stale session id, unsupported protocol version, bad JSON-RPC version) is +// the transport's own answer, passed on unchanged. The checks are therefore +// the transport's, not a copy of them that could drift. + +const ( + nativeMethodList = "skills/list" + nativeMethodGet = "skills/get" + nativeMethodRead = "resources/read" + + // nativeNotFoundCode is the code the extension's servers answer a missing + // skill or file with (the resource-not-found code). + nativeNotFoundCode = -32002 + // maxNativeRequestBytes bounds the body the interceptor reads. The three + // requests carry one URI or cursor; anything larger is not one of them and + // is left to the transport. + maxNativeRequestBytes = 64 << 10 +) + +// nativeSkillsServerOptions are the options a single-server instance with the +// native surface is built with: the extension and the resources capability +// it requires. +func nativeSkillsServerOptions() []mcpserver.ServerOption { + return []mcpserver.ServerOption{ + mcpserver.WithResourceCapabilities(false, false), + mcpserver.WithExtensions(map[string]any{skills.ExtensionKey: map[string]any{}}), + } +} + +// singleServerWantsNative reports whether /mcp/s/ should carry the +// native surface now: the feature is on and the server is not excluded +// (expose_skills: false). Whether a skill is available is decided per +// request, so a quarantined or disabled server keeps the announcement and +// lists nothing. +func (p *MCPProxyServer) singleServerWantsNative(name string) bool { + cfg := p.currentConfig() + if cfg == nil || !cfg.EnableSkills || p.skills() == nil { + return false + } + for _, sc := range cfg.Servers { + if sc != nil && sc.Name == name { + return sc.ExposeSkills == nil || *sc.ExposeSkills + } + } + return false +} + +// nativeSkillsRequest is the part of a JSON-RPC request the interceptor reads. +type nativeSkillsRequest struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` +} + +// parseNativeSkillsRequest returns the request when body is one JSON-RPC +// request (not a notification, not a batch) for one of the three methods. +func parseNativeSkillsRequest(body []byte) (*nativeSkillsRequest, bool) { + trimmed := bytes.TrimSpace(body) + if len(trimmed) == 0 || trimmed[0] != '{' { + return nil, false + } + var req nativeSkillsRequest + if err := json.Unmarshal(trimmed, &req); err != nil { + return nil, false + } + switch req.Method { + case nativeMethodList, nativeMethodGet, nativeMethodRead: + default: + return nil, false + } + if id := bytes.TrimSpace(req.ID); len(id) == 0 || bytes.Equal(id, []byte("null")) { + return nil, false + } + return &req, true +} + +// pingProbeBody is body with its method replaced by "ping"; everything else +// (jsonrpc, id, params with _meta) is kept, so the transport decides the era +// and the checks exactly as it would for the real request. +func pingProbeBody(body []byte) ([]byte, error) { + var obj map[string]json.RawMessage + if err := json.Unmarshal(body, &obj); err != nil { + return nil, err + } + obj["method"] = json.RawMessage(`"` + string(mcp.MethodPing) + `"`) + return json.Marshal(obj) +} + +// bufferedResponse records the transport's answer to the probe. +type bufferedResponse struct { + header http.Header + status int + body bytes.Buffer +} + +func newBufferedResponse() *bufferedResponse { + return &bufferedResponse{header: http.Header{}} +} + +func (b *bufferedResponse) Header() http.Header { return b.header } +func (b *bufferedResponse) Write(p []byte) (int, error) { + if b.status == 0 { + b.status = http.StatusOK + } + return b.body.Write(p) +} +func (b *bufferedResponse) WriteHeader(code int) { + if b.status == 0 { + b.status = code + } +} + +// accepted reports whether the transport answered the probe with a ping +// result: every check passed. +func (b *bufferedResponse) accepted() bool { + if b.status != http.StatusOK { + return false + } + var msg struct { + Result json.RawMessage `json:"result"` + Error json.RawMessage `json:"error"` + } + if err := json.Unmarshal(b.body.Bytes(), &msg); err != nil { + return false + } + return len(msg.Result) > 0 && len(msg.Error) == 0 +} + +// replay writes the recorded answer unchanged. +func (b *bufferedResponse) replay(w http.ResponseWriter) { + for k, v := range b.header { + w.Header()[k] = v + } + status := b.status + if status == 0 { + status = http.StatusOK + } + w.WriteHeader(status) + _, _ = w.Write(b.body.Bytes()) +} + +// nativeSkillsInterceptor answers skills/list, skills/get and resources/read +// on a single-server endpoint built with the native surface, after the +// transport (next) has accepted the request's ping probe. Every other request +// goes to next untouched. +func (p *MCPProxyServer) nativeSkillsInterceptor(ep *singleServerEndpoint, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.Body == nil { + next.ServeHTTP(w, r) + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, maxNativeRequestBytes+1)) + if err != nil || len(body) > maxNativeRequestBytes { + // Not one of ours (or unreadable): hand the transport the whole body. + r.Body = io.NopCloser(io.MultiReader(bytes.NewReader(body), r.Body)) + next.ServeHTTP(w, r) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) + req, ok := parseNativeSkillsRequest(body) + if !ok { + next.ServeHTTP(w, r) + return + } + probe, err := pingProbeBody(body) + if err != nil { + next.ServeHTTP(w, r) + return + } + pr := r.Clone(r.Context()) + pr.Body = io.NopCloser(bytes.NewReader(probe)) + pr.ContentLength = int64(len(probe)) + pr.Header = r.Header.Clone() + // A modern request must name its method in Mcp-Method; keep a header + // that agreed with the body agreeing with the probe, and leave a + // disagreeing one as it is so the transport refuses it. + if pr.Header.Get(mcp.HeaderMethod) == req.Method { + pr.Header.Set(mcp.HeaderMethod, string(mcp.MethodPing)) + } + rec := newBufferedResponse() + next.ServeHTTP(rec, pr) + if !rec.accepted() { + rec.replay(w) + return + } + for k, v := range rec.header { + if k == "Content-Length" || k == "Content-Type" { + continue + } + w.Header()[k] = v + } + p.answerNativeSkills(w, r, ep, req) + }) +} + +// nativeAnswer is one JSON-RPC answer: a result or an error. +type nativeAnswer struct { + result any + code int + msg string +} + +func writeNativeAnswer(w http.ResponseWriter, id json.RawMessage, a nativeAnswer) { + out := map[string]any{"jsonrpc": mcp.JSONRPC_VERSION, "id": id} + if a.code != 0 { + out["error"] = map[string]any{"code": a.code, "message": a.msg} + } else { + out["result"] = a.result + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(out) +} + +// nativeSkillEntry is one entry of the extension's listing. +type nativeSkillEntry struct { + URI string `json:"uri"` + Frontmatter json.RawMessage `json:"frontmatter"` + Resources []skills.FileRef `json:"resources"` +} + +// nativeEntryOf renders an available skill as the extension lists it, or nil +// when the output policy would change any upstream-written part of it (the +// address, a file address, the frontmatter): native answers are never +// rewritten, so such a skill is withheld. Only stored text files are listed, +// because only those are served. +func nativeEntryOf(clean func(string) string, sk *runtime.AvailableSkill) *nativeSkillEntry { + if sk == nil || sk.URI == "" || clean(sk.URI) != sk.URI { + return nil + } + fm := sk.Frontmatter + if len(bytes.TrimSpace(fm)) == 0 { + fm = json.RawMessage(`{}`) + } + if clean(string(fm)) != string(fm) { + return nil + } + e := &nativeSkillEntry{URI: sk.URI, Frontmatter: fm, Resources: []skills.FileRef{}} + for _, f := range sk.Files { + if !f.Text || !f.Stored || f.URI == "" { + continue + } + if clean(f.URI) != f.URI { + return nil + } + e.Resources = append(e.Resources, skills.FileRef{URI: f.URI, Digest: f.Digest, Size: f.Size}) + } + return e +} + +// answerNativeSkills answers one of the three methods for the endpoint's +// upstream and records one skill_access row, whatever the outcome. +func (p *MCPProxyServer) answerNativeSkills(w http.ResponseWriter, r *http.Request, ep *singleServerEndpoint, req *nativeSkillsRequest) { + ctx := r.Context() + p.recordMCPSurface() + start := time.Now() + sessionID := r.Header.Get(mcpserver.HeaderKeySessionID) + requestID := mintCorrelationID(req.Method) + + act := runtime.SkillAccessActivity{ + Source: string(storage.ActivitySourceMCP), Tool: req.Method, Server: ep.name, + SessionID: sessionID, RequestID: requestID, + } + switch req.Method { + case nativeMethodList: + act.Action = runtime.SkillActionList + case nativeMethodGet: + act.Action = runtime.SkillActionLoad + default: + act.Action = runtime.SkillActionRead + } + + a := p.nativeSkillsAnswer(ctx, ep, req, &act) + act.DurationMs = time.Since(start).Milliseconds() + p.emitSkillAccess(ctx, act) + writeNativeAnswer(w, req.ID, a) +} + +func (p *MCPProxyServer) nativeSkillsAnswer(ctx context.Context, ep *singleServerEndpoint, req *nativeSkillsRequest, act *runtime.SkillAccessActivity) nativeAnswer { + var params struct { + Cursor *string `json:"cursor"` + URI *string `json:"uri"` + } + if len(bytes.TrimSpace(req.Params)) > 0 && !bytes.Equal(bytes.TrimSpace(req.Params), []byte("null")) { + if err := json.Unmarshal(req.Params, ¶ms); err != nil { + act.Outcome = runtime.SkillAccessInvalid + return nativeAnswer{code: mcp.INVALID_PARAMS, msg: "invalid params"} + } + } + uri := "" + if req.Method != nativeMethodList { + if params.URI == nil || *params.URI == "" { + act.Outcome = runtime.SkillAccessInvalid + return nativeAnswer{code: mcp.INVALID_PARAMS, msg: "missing required parameter: uri"} + } + uri = *params.URI + act.SkillID = cutRunes(echoSkillID(uri), skillIDEchoMax) + } else if params.Cursor != nil && *params.Cursor != "" { + // The whole listing is one page; no cursor was ever issued. + act.Outcome = runtime.SkillAccessInvalid + return nativeAnswer{code: mcp.INVALID_PARAMS, msg: "invalid cursor"} + } + + notFound := func() nativeAnswer { + act.Outcome = runtime.SkillAccessNotFound + what := "skill" + if req.Method == nativeMethodRead { + what = "resource" + } + return nativeAnswer{code: nativeNotFoundCode, msg: what + " not found: " + echoSkillID(uri)} + } + + // The door admitted the caller; the answer is decided on the live state. + cat := p.skills() + if cat == nil || !p.skillsEnabled() || !p.singleServerAdmits(ctx, ep.name) { + if req.Method == nativeMethodList { + act.Outcome = runtime.SkillAccessSuccess + return nativeAnswer{result: map[string]any{"skills": []any{}}} + } + return notFound() + } + list, err := cat.ListAvailableSkills(ep.name) + if err != nil { + p.logger.Warn("native skills listing failed", zap.String("server", ep.name), zap.Error(err)) + act.Outcome = runtime.SkillAccessError + return nativeAnswer{code: mcp.INTERNAL_ERROR, msg: "skills are unavailable"} + } + pol := p.skillPolicy() + clean := p.skillWordCleaner(pol) + + switch req.Method { + case nativeMethodList: + entries := make([]*nativeSkillEntry, 0, len(list)) + for _, sk := range list { + if e := nativeEntryOf(clean, sk); e != nil { + entries = append(entries, e) + } + } + act.Outcome = runtime.SkillAccessSuccess + act.Results = len(entries) + act.Matches = len(entries) + return nativeAnswer{result: map[string]any{"skills": entries}} + + case nativeMethodGet: + for _, sk := range list { + if sk.URI != uri { + continue + } + e := nativeEntryOf(clean, sk) + if e == nil { + break + } + act.SkillID = sk.ID + act.SkillName = oneLine(sk.Name, skillNameMax) + act.Hash = sk.ApprovedHash + act.TotalSize = sk.TotalSize + act.Outcome = runtime.SkillAccessSuccess + return nativeAnswer{result: map[string]any{"skill": e}} + } + return notFound() + } + + // resources/read: the address must be a stored text file of an available + // skill of this server, listed under this exact address. + for _, sk := range list { + for _, f := range sk.Files { + if f.URI != uri { + continue + } + if nativeEntryOf(clean, sk) == nil { + return notFound() + } + act.SkillID = sk.ID + act.SkillName = oneLine(sk.Name, skillNameMax) + act.File = cutRunes(echoSkillID(f.RelPath), skillFileNameMax) + if !f.Text || !f.Stored { + act.Outcome = runtime.SkillAccessBinary + return nativeAnswer{code: nativeNotFoundCode, msg: "binary files are not served: " + echoSkillID(uri)} + } + return p.nativeReadFile(ctx, ep, cat, pol, sk, f, uri, act, notFound) + } + } + return notFound() +} + +// nativeReadFile reads one approved file and answers it byte for byte. +func (p *MCPProxyServer) nativeReadFile(ctx context.Context, ep *singleServerEndpoint, cat skillsCatalog, pol skillOutputPolicy, + sk *runtime.AvailableSkill, f storage.SkillFile, uri string, act *runtime.SkillAccessActivity, notFound func() nativeAnswer) nativeAnswer { + data, meta, got, err := cat.AvailableSkillFile(ep.name, sk.Path, f.RelPath) + switch { + case err == nil && got != nil: + case errors.Is(err, runtime.ErrSkillFileBinary): + act.Outcome = runtime.SkillAccessBinary + return nativeAnswer{code: nativeNotFoundCode, msg: "binary files are not served: " + echoSkillID(uri)} + case errors.Is(err, runtime.ErrSkillStoredCopyDamaged): + ans := notFound() + act.Outcome = runtime.SkillAccessDamaged + return ans + default: + if err != nil && !errors.Is(err, runtime.ErrSkillNotFound) { + p.logger.Warn("native skill read failed", zap.String("server", ep.name), zap.Error(err)) + } + return notFound() + } + // The listing the client holds names this digest; a skill approved again + // in between has other files, and the old address answers not found. + if meta.Digest != "" && meta.Digest != f.Digest { + return notFound() + } + act.Hash = got.ApprovedHash + act.TotalSize = int64(len(data)) + + // Native reads are never rewritten (FR-029a): what the policy would block + // or change is withheld. + served := p.servedSkillText(pol, ep.name, meta.Digest, data) + if served.blocked || served.text != nil { + reason := served.reason + if reason == "" { + reason = "native skill reads are served unchanged or not at all" + } + p.emitActivityPolicyDecision(ctx, ep.name, nativeMethodRead, act.SessionID, act.RequestID, + "blocked", reason, telemetry.BlockReasonOutputSanitisation) + act.Outcome = runtime.SkillAccessBlocked + return nativeAnswer{code: mcp.INTERNAL_ERROR, msg: "skill output blocked by the output sanitisation policy"} + } + + text := string(data) + act.Bytes = int64(len(data)) + // Sensitive-data detection records findings on what was delivered; the + // bytes are not altered. + act.DetectionText = text + act.Outcome = runtime.SkillAccessSuccess + item := map[string]any{"uri": uri, "text": text} + if mt := nativeMimeType(f.RelPath); mt != "" { + item["mimeType"] = mt + } + return nativeAnswer{result: map[string]any{"contents": []any{item}}} +} + +// nativeMimeType is the media type answered for a text file, by extension. +func nativeMimeType(rel string) string { + switch { + case strings.HasSuffix(rel, ".md"): + return "text/markdown" + default: + return "text/plain" + } +} diff --git a/internal/server/skills_native_test.go b/internal/server/skills_native_test.go new file mode 100644 index 000000000..3cd02a2d4 --- /dev/null +++ b/internal/server/skills_native_test.go @@ -0,0 +1,537 @@ +package server + +import ( + "bufio" + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io" + "net/http" + "strings" + "sync" + "testing" + "time" + + "github.com/mark3labs/mcp-go/mcp" + mcpserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/skills" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/skills/skillstest" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Spec 125 PR-5 (T047, T048, T050): the native skills surface on +// /mcp/s/, driven with a raw JSON-RPC client over HTTP against a real +// Server whose upstream is the skills fixture. + +// rawMCP is a minimal Streamable HTTP client: it speaks the legacy handshake +// mcpproxy serves and nothing else, so every check is visible. +type rawMCP struct { + t *testing.T + url string + sid string + id int +} + +type rawRPCError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +type rawReply struct { + status int + header http.Header + body []byte + result json.RawMessage + err *rawRPCError +} + +func newRawMCP(t *testing.T, url string) *rawMCP { return &rawMCP{t: t, url: url} } + +// send posts one message with the given session id and protocol header. +func (c *rawMCP) send(sid, proto string, msg map[string]any) rawReply { + c.t.Helper() + body, err := json.Marshal(msg) + require.NoError(c.t, err) + req, err := http.NewRequest(http.MethodPost, c.url, bytes.NewReader(body)) + require.NoError(c.t, err) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + if sid != "" { + req.Header.Set("Mcp-Session-Id", sid) + } + if proto != "" { + req.Header.Set("Mcp-Protocol-Version", proto) + } + resp, err := http.DefaultClient.Do(req) + require.NoError(c.t, err) + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + require.NoError(c.t, err) + out := rawReply{status: resp.StatusCode, header: resp.Header, body: raw} + payload := raw + if strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") { + for _, line := range strings.Split(string(raw), "\n") { + if d, ok := strings.CutPrefix(line, "data: "); ok { + payload = []byte(d) + } + } + } + var msgOut struct { + Result json.RawMessage `json:"result"` + Error *rawRPCError `json:"error"` + } + if json.Unmarshal(payload, &msgOut) == nil { + out.result, out.err = msgOut.Result, msgOut.Error + } + return out +} + +func (c *rawMCP) nextID() int { c.id++; return c.id } + +// initialize runs the handshake and keeps the session id. +func (c *rawMCP) initialize() (caps map[string]any, instructions string) { + c.t.Helper() + r := c.send("", "", map[string]any{"jsonrpc": "2.0", "id": c.nextID(), "method": "initialize", "params": map[string]any{ + "protocolVersion": mcp.LATEST_LEGACY_PROTOCOL_VERSION, "capabilities": map[string]any{}, + "clientInfo": map[string]any{"name": "native-skills-test", "version": "1"}, + }}) + require.Equal(c.t, http.StatusOK, r.status, string(r.body)) + require.Nil(c.t, r.err, string(r.body)) + c.sid = r.header.Get("Mcp-Session-Id") + require.NotEmpty(c.t, c.sid) + var res struct { + Capabilities map[string]any `json:"capabilities"` + Instructions string `json:"instructions"` + } + require.NoError(c.t, json.Unmarshal(r.result, &res), string(r.body)) + c.send(c.sid, mcp.LATEST_LEGACY_PROTOCOL_VERSION, map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"}) + return res.Capabilities, res.Instructions +} + +func (c *rawMCP) call(method string, params map[string]any) rawReply { + c.t.Helper() + msg := map[string]any{"jsonrpc": "2.0", "id": c.nextID(), "method": method} + if params != nil { + msg["params"] = params + } + return c.send(c.sid, mcp.LATEST_LEGACY_PROTOCOL_VERSION, msg) +} + +func hasSkillsExtension(caps map[string]any) bool { + ext, _ := caps["extensions"].(map[string]any) + _, ok := ext[skills.ExtensionKey] + return ok +} + +type nativeListing struct { + Skills []struct { + URI string `json:"uri"` + Frontmatter map[string]any `json:"frontmatter"` + Resources []struct { + URI string `json:"uri"` + Digest string `json:"digest"` + Size int64 `json:"size"` + } `json:"resources"` + } `json:"skills"` +} + +func (g *realSkills) singleURL() string { + return g.env.baseURL() + "/mcp/s/" + realSkillsSrv +} + +func (g *realSkills) nativeRows(t *testing.T) []*storage.ActivityRecord { + t.Helper() + f := storage.DefaultActivityFilter() + f.Types = []string{string(storage.ActivityTypeSkillAccess)} + rows, _, err := g.rt.StorageManager().ListActivities(f) + require.NoError(t, err) + var out []*storage.ActivityRecord + for _, r := range rows { + switch r.ToolName { + case nativeMethodList, nativeMethodGet, nativeMethodRead: + out = append(out, r) + } + } + return out +} + +func newNativeSkills(t *testing.T) *realSkills { + t.Helper() + g := newRealSkills(t, func(fx *skillstest.Fixture) { + fx.AddSkill(skillstest.Skill{Path: "pdf", Files: map[string][]byte{ + "SKILL.md": realSkillMD("pdf", "reads pdf files", "Use the script.\n«ünïcødé» line"), + "scripts/x.py": []byte("print('hello')\n"), + }}) + fx.AddSkill(skillstest.Skill{Path: "held", Files: map[string][]byte{ + "SKILL.md": realSkillMD("held", "not approved", "HELD-TEXT"), + }}) + }, nil) + g.approve(t, "pdf") + return g +} + +// T047: announced, exact listing with upstream addresses, byte-exact reads, +// held skill absent, aggregated endpoints never announce, one activity row per +// access including not-found. +func TestNativeSkills_SingleServerSurface(t *testing.T) { + g := newNativeSkills(t) + c := newRawMCP(t, g.singleURL()) + caps, _ := c.initialize() + require.True(t, hasSkillsExtension(caps), "the extension is announced: %v", caps) + require.Contains(t, caps, "resources", "the extension requires the resources capability") + + list := c.call(nativeMethodList, map[string]any{}) + require.Nil(t, list.err, string(list.body)) + var listing nativeListing + require.NoError(t, json.Unmarshal(list.result, &listing), string(list.body)) + require.Len(t, listing.Skills, 1, "exactly the approved skill: %s", list.body) + entry := listing.Skills[0] + assert.Equal(t, "skill://pdf/SKILL.md", entry.URI, "the upstream's address") + assert.Equal(t, "pdf", entry.Frontmatter["name"]) + require.Len(t, entry.Resources, 2) + assert.NotContains(t, string(list.body), "held") + + for _, res := range entry.Resources { + read := c.call(nativeMethodRead, map[string]any{"uri": res.URI}) + require.Nil(t, read.err, string(read.body)) + var contents struct { + Contents []struct { + URI string `json:"uri"` + Text string `json:"text"` + } `json:"contents"` + } + require.NoError(t, json.Unmarshal(read.result, &contents)) + require.Len(t, contents.Contents, 1) + assert.Equal(t, res.URI, contents.Contents[0].URI) + data := []byte(contents.Contents[0].Text) + sum := sha256.Sum256(data) + assert.Equal(t, res.Digest, "sha256:"+hex.EncodeToString(sum[:]), "byte for byte: %s", res.URI) + assert.Equal(t, res.Size, int64(len(data))) + } + + get := c.call(nativeMethodGet, map[string]any{"uri": "skill://pdf/SKILL.md"}) + require.Nil(t, get.err, string(get.body)) + assert.Contains(t, string(get.result), `"uri":"skill://pdf/SKILL.md"`) + + // The held skill: absent, and not found by address. + for _, r := range []rawReply{ + c.call(nativeMethodGet, map[string]any{"uri": "skill://held/SKILL.md"}), + c.call(nativeMethodRead, map[string]any{"uri": "skill://held/SKILL.md"}), + c.call(nativeMethodRead, map[string]any{"uri": "skill://pdf/nope.md"}), + } { + require.NotNil(t, r.err, string(r.body)) + assert.Equal(t, nativeNotFoundCode, r.err.Code) + assert.Contains(t, r.err.Message, "not found") + assert.NotContains(t, string(r.body), "HELD-TEXT") + } + + // Tools still work on the same session. + tools := c.call("tools/list", nil) + require.Nil(t, tools.err, string(tools.body)) + + // Aggregated endpoints never announce the extension, and do not answer it. + for _, path := range []string{"/mcp", "/mcp/all"} { + agg := newRawMCP(t, g.env.baseURL()+path) + caps, _ := agg.initialize() + assert.False(t, hasSkillsExtension(caps), "%s must not announce the extension", path) + r := agg.call(nativeMethodList, map[string]any{}) + require.NotNil(t, r.err, "%s: %s", path, r.body) + assert.Equal(t, mcp.METHOD_NOT_FOUND, r.err.Code) + } + + // One row per native access, not-found included: list, 2 reads, get, 3 refusals. + var rows []*storage.ActivityRecord + require.Eventually(t, func() bool { rows = g.nativeRows(t); return len(rows) >= 7 }, 10*time.Second, 50*time.Millisecond) + assert.Len(t, rows, 7) + outcomes := map[string]int{} + for _, r := range rows { + outcomes[r.ToolName+"/"+r.Metadata["outcome"].(string)]++ + assert.Equal(t, realSkillsSrv, r.ServerName) + assert.Equal(t, c.sid, r.SessionID, "the row carries the caller's session") + } + assert.Equal(t, map[string]int{ + "skills/list/success": 1, + "resources/read/success": 2, + "skills/get/success": 1, + "skills/get/not_found": 1, + "resources/read/not_found": 2, + }, outcomes) +} + +// T048: each extension method gets exactly the refusal tools/call gets for a +// missing session id, a foreign one and an unsupported protocol version. +func TestNativeSkills_RefusalParityWithToolsCall(t *testing.T) { + g := newNativeSkills(t) + c := newRawMCP(t, g.singleURL()) + caps, _ := c.initialize() + require.True(t, hasSkillsExtension(caps)) + + other := newSingleServerSessionIDs("other", 0).Generate() + stale := newSingleServerSessionIDs(realSkillsSrv, 7).Generate() + cases := []struct { + name, sid, proto string + meta bool + }{ + {"missing session id", "", mcp.LATEST_LEGACY_PROTOCOL_VERSION, false}, + {"foreign session id", other, mcp.LATEST_LEGACY_PROTOCOL_VERSION, false}, + {"session id of another generation", stale, mcp.LATEST_LEGACY_PROTOCOL_VERSION, false}, + {"malformed session id", "mcp-session-nope", mcp.LATEST_LEGACY_PROTOCOL_VERSION, false}, + {"unsupported protocol version", c.sid, mcp.ProtocolVersion20260728, true}, + {"protocol version header without meta", c.sid, mcp.ProtocolVersion20260728, false}, + } + methods := map[string]map[string]any{ + "tools/call": {"name": "echo", "arguments": map[string]any{}}, + nativeMethodList: {}, + nativeMethodGet: {"uri": "skill://pdf/SKILL.md"}, + nativeMethodRead: {"uri": "skill://pdf/SKILL.md"}, + } + before := len(g.nativeRows(t)) + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var want rawReply + for _, m := range []string{"tools/call", nativeMethodList, nativeMethodGet, nativeMethodRead} { + params := map[string]any{} + for k, v := range methods[m] { + params[k] = v + } + if tc.meta { + params["_meta"] = map[string]any{"io.modelcontextprotocol/protocolVersion": tc.proto} + } + got := c.send(tc.sid, tc.proto, map[string]any{"jsonrpc": "2.0", "id": 99, "method": m, "params": params}) + assert.GreaterOrEqual(t, got.status, 400, "%s is refused: %s", m, got.body) + if m == "tools/call" { + want = got + continue + } + assert.Equal(t, want.status, got.status, "%s status like tools/call", m) + assert.Equal(t, strings.ReplaceAll(string(want.body), "tools/call", "ping"), + strings.ReplaceAll(string(got.body), m, "ping"), "%s body like tools/call", m) + assert.NotContains(t, string(got.body), "skill://pdf", "a refusal carries no skill") + } + }) + } + assert.Equal(t, before, len(g.nativeRows(t)), "a refused request reads nothing and records no skill access") +} + +// openStream opens the legacy standalone GET stream of a session and reports +// on the returned channel when the server closes it. +func openStream(t *testing.T, url, sid string) (closed <-chan struct{}, cancel func()) { + t.Helper() + ctx, stop := context.WithCancel(context.Background()) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + require.NoError(t, err) + req.Header.Set("Accept", "text/event-stream") + req.Header.Set("Mcp-Session-Id", sid) + req.Header.Set("Mcp-Protocol-Version", mcp.LATEST_LEGACY_PROTOCOL_VERSION) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + require.Equal(t, http.StatusOK, resp.StatusCode) + done := make(chan struct{}) + go func() { + defer close(done) + defer resp.Body.Close() + r := bufio.NewReader(resp.Body) + for { + if _, err := r.ReadString('\n'); err != nil { + return + } + } + }() + return done, stop +} + +// T050: off -> on -> off on one endpoint. At each step the new session sees +// the right capabilities, the previous step's session is refused, its stream +// is closed, and transports do not accumulate. +func TestNativeSkills_EndpointFollowsTheSwitch(t *testing.T) { + g := newNativeSkills(t) + url := g.singleURL() + + type step struct { + name string + enable bool + } + var prev *rawMCP + var prevClosed <-chan struct{} + for i, st := range []step{{"on", true}, {"off", false}, {"on again", true}, {"off again", false}} { + if i > 0 { + g.commitGlobal(t, func(c *config.Config) { c.EnableSkills = st.enable }) + if i%2 == 0 { + // Every other step through the reload hook, the others lazily on + // the next request: both paths must retire. + g.p.RefreshSkillsAvailability() + } + } + c := newRawMCP(t, url) + caps, _ := c.initialize() + assert.Equal(t, st.enable, hasSkillsExtension(caps), "step %s: announcement", st.name) + list := c.call(nativeMethodList, map[string]any{}) + if st.enable { + require.Nil(t, list.err, "step %s: %s", st.name, list.body) + assert.Contains(t, string(list.result), "skill://pdf/SKILL.md") + read := c.call(nativeMethodRead, map[string]any{"uri": "skill://pdf/scripts/x.py"}) + require.Nil(t, read.err, string(read.body)) + assert.Contains(t, string(read.result), "print('hello')") + } else { + require.NotNil(t, list.err, "step %s: %s", st.name, list.body) + assert.Equal(t, mcp.METHOD_NOT_FOUND, list.err.Code, "off: the method is unknown") + } + + if prev != nil { + old := prev.call("tools/list", nil) + assert.Equal(t, http.StatusNotFound, old.status, "step %s: the previous session is refused: %s", st.name, old.body) + select { + case <-prevClosed: + case <-time.After(10 * time.Second): + t.Fatalf("step %s: the previous step's stream is still open", st.name) + } + } + assert.LessOrEqual(t, g.p.singleServerTransportCount(), 1, "step %s: transports do not accumulate", st.name) + + var cancel func() + prevClosed, cancel = openStream(t, url, c.sid) + t.Cleanup(cancel) + prev = c + } +} + +// T050: acquisition racing retirement never leaves a transport behind its +// instance. +func TestNativeSkills_AcquireRacesRetire(t *testing.T) { + g := newNativeSkills(t) + newTransport := func(srv *mcpserver.MCPServer, gen uint64) *mcpserver.StreamableHTTPServer { + return mcpserver.NewStreamableHTTPServer(srv, singleServerStreamableOptions(nil, realSkillsSrv, gen)...) + } + var wg sync.WaitGroup + stop := make(chan struct{}) + var mu sync.Mutex + var acquired []*singleServerEndpoint + for w := 0; w < 8; w++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + ep, ok := g.p.acquireSingleServerEndpoint(realSkillsSrv, newTransport) + if ok { + mu.Lock() + acquired = append(acquired, ep) + mu.Unlock() + } + } + }() + } + on := true + for i := 0; i < 40; i++ { + on = !on + g.commitGlobal(t, func(c *config.Config) { c.EnableSkills = on }) + g.p.retireStaleNativeSurfaces() + } + close(stop) + wg.Wait() + + require.LessOrEqual(t, g.p.singleServerTransportCount(), 1) + g.p.singleServersMu.Lock() + live := g.p.singleServers[realSkillsSrv] + g.p.singleServersMu.Unlock() + for _, ep := range acquired { + if live != nil && ep.server == live.server { + assert.Same(t, live.transport, ep.transport, "the live instance has exactly one transport") + continue + } + select { + case <-ep.retired: + default: + t.Fatalf("an acquired endpoint that is not live was never retired") + } + } +} + +// T050: an initialize that acquired its endpoint before a retirement answers +// with that upstream's instructions, never the aggregate ones. +func TestNativeSkills_PausedInitializeKeepsItsUpstream(t *testing.T) { + g := newNativeSkills(t) + url := g.singleURL() + + entered, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + hook := func(string) { + paused := false + once.Do(func() { paused = true }) + if paused { + close(entered) + <-release + } + } + g.env.proxyServer.singleServerAcquired.Store(&hook) + t.Cleanup(func() { g.env.proxyServer.singleServerAcquired.Store(nil) }) + + type initOut struct { + caps map[string]any + instructions string + } + out := make(chan initOut, 1) + go func() { + c := newRawMCP(t, url) + caps, instr := c.initialize() + out <- initOut{caps, instr} + }() + <-entered + g.commitGlobal(t, func(c *config.Config) { c.EnableSkills = false }) + g.p.RefreshSkillsAvailability() + g.p.singleServersMu.Lock() + _, cached := g.p.singleServers[realSkillsSrv] + g.p.singleServersMu.Unlock() + require.False(t, cached, "the endpoint was retired while the initialize was paused") + close(release) + + got := <-out + assert.True(t, hasSkillsExtension(got.caps), "served by the instance it acquired") + assert.NotContains(t, got.instructions, "retrieve_tools", "never the aggregate instructions") + assert.NotContains(t, got.instructions, "mcpproxy") +} + +// An excluded server (expose_skills: false) does not announce the extension; +// a skill changed upstream is withdrawn natively until it is approved again, +// and its new bytes are never served (SC-002). +func TestNativeSkills_ExcludedAndChangedSkills(t *testing.T) { + g := newNativeSkills(t) + url := g.singleURL() + + g.fx.Mutate("pdf", "scripts/x.py", []byte("print('CHANGED')\n")) + g.refreshUntil(t, func() bool { return g.rec(t, "pdf").Status == storage.SkillStatusChanged }) + c := newRawMCP(t, url) + caps, _ := c.initialize() + require.True(t, hasSkillsExtension(caps)) + list := c.call(nativeMethodList, map[string]any{}) + require.Nil(t, list.err, string(list.body)) + assert.JSONEq(t, `{"skills":[]}`, string(list.result), "a changed skill is not listed") + read := c.call(nativeMethodRead, map[string]any{"uri": "skill://pdf/scripts/x.py"}) + require.NotNil(t, read.err) + assert.Equal(t, nativeNotFoundCode, read.err.Code) + assert.NotContains(t, string(read.body), "CHANGED") + + g.approve(t, "pdf") + read = c.call(nativeMethodRead, map[string]any{"uri": "skill://pdf/scripts/x.py"}) + require.Nil(t, read.err, string(read.body)) + assert.Contains(t, string(read.result), "CHANGED", "served again once the change is approved") + + exclude := false + g.commitServer(t, func(sc *config.ServerConfig) { sc.ExposeSkills = &exclude }) + c2 := newRawMCP(t, url) + caps, _ = c2.initialize() + assert.False(t, hasSkillsExtension(caps), "an excluded server does not announce the extension") + r := c2.call(nativeMethodRead, map[string]any{"uri": "skill://pdf/scripts/x.py"}) + require.NotNil(t, r.err) + assert.Equal(t, mcp.METHOD_NOT_FOUND, r.err.Code) +} diff --git a/specs/125-skills-over-mcp/tasks.md b/specs/125-skills-over-mcp/tasks.md index 12f9f0253..2ccbb2d07 100644 --- a/specs/125-skills-over-mcp/tasks.md +++ b/specs/125-skills-over-mcp/tasks.md @@ -112,11 +112,11 @@ description: "Task list for Skills over MCP (spec 125)" ## PR-5: Native surface on the single-server endpoint (US5) -- [ ] T047 [P] [US5] Tests with a raw client against `/mcp/s/`: extension announced only when the feature is on and the server not excluded; listing and single entry contain exactly the available skills with upstream addresses; file read byte-exact against the listed digest; held skill absent and not found; aggregated endpoints never announce; activity rows for list, get and read including not-found -- [ ] T048 [P] [US5] Parity tests: each extension method with a missing session id, a foreign one and an unsupported protocol version gets the refusal `tools/call` gets -- [ ] T049 [US5] Extract the transport's method, protocol-version and session checks for reuse; implement the interceptor inside `serveSingleServer` and the resource template in `internal/server/skills_native.go` (plan D14) -- [ ] T050 [US5] Endpoint lifecycle: per-endpoint lock, combined acquisition of instance, transport and generation, retirement, generation in session ids, upstream name bound to the instance; tests for off → on → off (old session refused, old stream closed, transports do not accumulate), the acquisition-versus-retirement race and the paused `initialize` -- [ ] T051 [US5] Manual check with a client that consumes the extension; docs section "Native skills on single-server endpoints" +- [x] T047 [P] [US5] Tests with a raw client against `/mcp/s/`: extension announced only when the feature is on and the server not excluded; listing and single entry contain exactly the available skills with upstream addresses; file read byte-exact against the listed digest; held skill absent and not found; aggregated endpoints never announce; activity rows for list, get and read including not-found +- [x] T048 [P] [US5] Parity tests: each extension method with a missing session id, a foreign one and an unsupported protocol version gets the refusal `tools/call` gets +- [x] T049 [US5] Extract the transport's method, protocol-version and session checks for reuse; implement the interceptor inside `serveSingleServer` and the resource template in `internal/server/skills_native.go` (plan D14) +- [x] T050 [US5] Endpoint lifecycle: per-endpoint lock, combined acquisition of instance, transport and generation, retirement, generation in session ids, upstream name bound to the instance; tests for off → on → off (old session refused, old stream closed, transports do not accumulate), the acquisition-versus-retirement race and the paused `initialize` +- [x] T051 [US5] Manual check with a client that consumes the extension; docs section "Native skills on single-server endpoints" --- From 7fd333f6dea7bc8cb8e61c4a33953bf124c34118 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 12:52:20 +0200 Subject: [PATCH 2/8] fix(skills): check native frontmatter against the output policy decoded The stored frontmatter JSON escapes control characters, so checking its serialized form let a decoded ESC through a stripping policy. Every key and string value is now checked decoded (review round 1). Co-Authored-By: Claude Opus 5.5 --- internal/server/skills_native.go | 35 +++++++++++++++++++- internal/server/skills_native_test.go | 46 +++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/internal/server/skills_native.go b/internal/server/skills_native.go index ce9fbccc0..361c49e7e 100644 --- a/internal/server/skills_native.go +++ b/internal/server/skills_native.go @@ -271,7 +271,7 @@ func nativeEntryOf(clean func(string) string, sk *runtime.AvailableSkill) *nativ if len(bytes.TrimSpace(fm)) == 0 { fm = json.RawMessage(`{}`) } - if clean(string(fm)) != string(fm) { + if !frontmatterUnchangedBy(clean, fm) { return nil } e := &nativeSkillEntry{URI: sk.URI, Frontmatter: fm, Resources: []skills.FileRef{}} @@ -287,6 +287,39 @@ func nativeEntryOf(clean func(string) string, sk *runtime.AvailableSkill) *nativ return e } +// frontmatterUnchangedBy reports whether the policy leaves every key and every +// string value of the frontmatter unchanged. The check runs on the decoded +// text: the stored JSON escapes control characters (an ESC is "\u001b" there), +// so checking the serialized form would let through what a client decodes. +// Frontmatter that does not decode is not served. +func frontmatterUnchangedBy(clean func(string) string, fm json.RawMessage) bool { + var doc any + if err := json.Unmarshal(fm, &doc); err != nil { + return false + } + var walk func(v any) bool + walk = func(v any) bool { + switch t := v.(type) { + case string: + return clean(t) == t + case map[string]any: + for k, val := range t { + if clean(k) != k || !walk(val) { + return false + } + } + case []any: + for _, val := range t { + if !walk(val) { + return false + } + } + } + return true + } + return walk(doc) +} + // answerNativeSkills answers one of the three methods for the endpoint's // upstream and records one skill_access row, whatever the outcome. func (p *MCPProxyServer) answerNativeSkills(w http.ResponseWriter, r *http.Request, ep *singleServerEndpoint, req *nativeSkillsRequest) { diff --git a/internal/server/skills_native_test.go b/internal/server/skills_native_test.go index 3cd02a2d4..03513fcb9 100644 --- a/internal/server/skills_native_test.go +++ b/internal/server/skills_native_test.go @@ -20,6 +20,7 @@ import ( "github.com/stretchr/testify/require" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/runtime" "github.com/smart-mcp-proxy/mcpproxy-go/internal/skills" "github.com/smart-mcp-proxy/mcpproxy-go/internal/skills/skillstest" "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" @@ -535,3 +536,48 @@ func TestNativeSkills_ExcludedAndChangedSkills(t *testing.T) { require.NotNil(t, r.err) assert.Equal(t, mcp.METHOD_NOT_FOUND, r.err.Code) } + +// Native answers are never rewritten: under a policy that strips control +// characters, a skill whose decoded frontmatter carries one is withheld from +// the listing (the stored JSON escapes it, so the check must decode), and a +// file the policy would change is refused rather than served changed. +func TestNativeSkills_PolicyWithholdsInsteadOfRewriting(t *testing.T) { + strip := &config.OutputSanitisationConfig{ResponseAction: "spotlight", StripControlChars: true, + StripClasses: []string{"ansi", "c0c1"}, MaxRedactions: 100} + + t.Run("frontmatter is checked decoded", func(t *testing.T) { + fx := newSkillFixture(t) + fx.proxy.config.OutputSanitisation = strip + clean := fx.proxy.skillWordCleaner(fx.proxy.skillPolicy()) + sk := &runtime.AvailableSkill{ + URI: "skill://a/SKILL.md", Path: "a", + Frontmatter: json.RawMessage(`{"name":"a","note":"\u001b[31mRED\u001b[0m"}`), + } + assert.Nil(t, nativeEntryOf(clean, sk), "an escaped ESC in a frontmatter value withholds the skill") + sk.Frontmatter = json.RawMessage(`{"name":"a","\u001bkey":"v"}`) + assert.Nil(t, nativeEntryOf(clean, sk), "and in a key") + sk.Frontmatter = json.RawMessage(`{"name":"a","tags":["ok","\u001b[1m"]}`) + assert.Nil(t, nativeEntryOf(clean, sk), "and in a list") + sk.Frontmatter = json.RawMessage(`{"name":"a","description":"plain"}`) + assert.NotNil(t, nativeEntryOf(clean, sk), "clean frontmatter is listed") + }) + + t.Run("a file the policy would change is refused", func(t *testing.T) { + g := newRealSkills(t, func(fx *skillstest.Fixture) { + fx.AddSkill(skillstest.Skill{Path: "esc", Files: map[string][]byte{ + "SKILL.md": realSkillMD("esc", "has escapes", "plain"), + "ref.txt": []byte("before \x1b[31mRED\x1b[0m after\n"), + }}) + }, nil) + g.approve(t, "esc") + g.commitGlobal(t, func(c *config.Config) { c.OutputSanitisation = strip }) + c := newRawMCP(t, g.singleURL()) + c.initialize() + read := c.call(nativeMethodRead, map[string]any{"uri": "skill://esc/ref.txt"}) + require.NotNil(t, read.err, string(read.body)) + assert.Contains(t, read.err.Message, "blocked by the output sanitisation policy") + assert.NotContains(t, string(read.body), "RED") + ok := c.call(nativeMethodRead, map[string]any{"uri": "skill://esc/SKILL.md"}) + require.Nil(t, ok.err, "a file the policy leaves alone is served: %s", ok.body) + }) +} From 48dfe66a8f8752b4ef84b587e54472a13c705df5 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 12:54:51 +0200 Subject: [PATCH 3/8] fix(skills): decide the native surface again after waiting for the build locks A first request that read the switch, then waited behind a catalog rebuild while a refresh ran, built an endpoint with the old capabilities (review round 2). Co-Authored-By: Claude Opus 5.5 --- internal/server/mcp_single_server.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/internal/server/mcp_single_server.go b/internal/server/mcp_single_server.go index e5eb0ea0d..890a4f46e 100644 --- a/internal/server/mcp_single_server.go +++ b/internal/server/mcp_single_server.go @@ -122,6 +122,10 @@ func (p *MCPProxyServer) singleServerSurfaceFor(name string) *singleServerSurfac p.singleServersMu.Unlock() shutdownSingleServerTransport(stale) + // Registered first so it runs after both locks are released. + var staleAfterWait *mcpserver.StreamableHTTPServer + defer func() { shutdownSingleServerTransport(staleAfterWait) }() + // Lock order: directRefreshMu, then singleServersMu (the rebuild path // holds the first and takes the second). Holding directRefreshMu while // populating means a rebuild cannot publish a newer catalog between this @@ -131,8 +135,14 @@ func (p *MCPProxyServer) singleServerSurfaceFor(name string) *singleServerSurfac p.singleServersMu.Lock() defer p.singleServersMu.Unlock() + // The switch may have moved while this request waited for the locks (and + // a refresh that ran meanwhile found nothing to retire): decide again. + wantNative = p.singleServerWantsNative(name) if s, ok := p.singleServers[name]; ok { - return s + if s.native == wantNative { + return s + } + staleAfterWait = p.retireSingleServerLocked(name) } opts := p.singleServerOpts if wantNative { From acbc3a67c41aea454002a822f1c11cbd0f44f696 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 12:58:09 +0200 Subject: [PATCH 4/8] test(skills): make the native-surface tests prove what they claim Modern-version parity asserts the version refusal itself; the stream must be an open SSE stream before the toggle; the race test asserts acquisitions interleave with retirements; the paused initialize checks the upstream's exact instructions (fixture gains SetInstructions) and is bounded; skills/get is compared with the listed entry (review round 3). Co-Authored-By: Claude Opus 5.5 --- internal/server/skills_native_test.go | 94 +++++++++++++++++++++++---- internal/skills/skillstest/fixture.go | 20 +++++- 2 files changed, 99 insertions(+), 15 deletions(-) diff --git a/internal/server/skills_native_test.go b/internal/server/skills_native_test.go index 03513fcb9..d8db987af 100644 --- a/internal/server/skills_native_test.go +++ b/internal/server/skills_native_test.go @@ -56,6 +56,12 @@ func newRawMCP(t *testing.T, url string) *rawMCP { return &rawMCP{t: t, url: url // send posts one message with the given session id and protocol header. func (c *rawMCP) send(sid, proto string, msg map[string]any) rawReply { + c.t.Helper() + return c.sendWith(sid, proto, nil, msg) +} + +// sendWith is send with extra request headers. +func (c *rawMCP) sendWith(sid, proto string, extra map[string]string, msg map[string]any) rawReply { c.t.Helper() body, err := json.Marshal(msg) require.NoError(c.t, err) @@ -69,6 +75,9 @@ func (c *rawMCP) send(sid, proto string, msg map[string]any) rawReply { if proto != "" { req.Header.Set("Mcp-Protocol-Version", proto) } + for k, v := range extra { + req.Header.Set(k, v) + } resp, err := http.DefaultClient.Do(req) require.NoError(c.t, err) defer resp.Body.Close() @@ -162,9 +171,12 @@ func (g *realSkills) nativeRows(t *testing.T) []*storage.ActivityRecord { return out } +const nativeUpstreamInstructions = "Prefer the pdf skill for reading documents." + func newNativeSkills(t *testing.T) *realSkills { t.Helper() g := newRealSkills(t, func(fx *skillstest.Fixture) { + fx.SetInstructions(nativeUpstreamInstructions) fx.AddSkill(skillstest.Skill{Path: "pdf", Files: map[string][]byte{ "SKILL.md": realSkillMD("pdf", "reads pdf files", "Use the script.\n«ünïcødé» line"), "scripts/x.py": []byte("print('hello')\n"), @@ -218,7 +230,16 @@ func TestNativeSkills_SingleServerSurface(t *testing.T) { get := c.call(nativeMethodGet, map[string]any{"uri": "skill://pdf/SKILL.md"}) require.Nil(t, get.err, string(get.body)) - assert.Contains(t, string(get.result), `"uri":"skill://pdf/SKILL.md"`) + var single struct { + Skill json.RawMessage `json:"skill"` + } + require.NoError(t, json.Unmarshal(get.result, &single), string(get.body)) + var listed struct { + Skills []json.RawMessage `json:"skills"` + } + require.NoError(t, json.Unmarshal(list.result, &listed)) + require.Len(t, listed.Skills, 1) + assert.JSONEq(t, string(listed.Skills[0]), string(single.Skill), "the single entry is the listed entry") // The held skill: absent, and not found by address. for _, r := range []rawReply{ @@ -286,6 +307,9 @@ func TestNativeSkills_RefusalParityWithToolsCall(t *testing.T) { {"unsupported protocol version", c.sid, mcp.ProtocolVersion20260728, true}, {"protocol version header without meta", c.sid, mcp.ProtocolVersion20260728, false}, } + // The modern case is otherwise a valid modern request (Mcp-Method agrees + // with the body), so the refusal is the one for the version itself. + wantCode := map[string]int{"unsupported protocol version": mcp.UNSUPPORTED_PROTOCOL_VERSION} methods := map[string]map[string]any{ "tools/call": {"name": "echo", "arguments": map[string]any{}}, nativeMethodList: {}, @@ -304,8 +328,16 @@ func TestNativeSkills_RefusalParityWithToolsCall(t *testing.T) { if tc.meta { params["_meta"] = map[string]any{"io.modelcontextprotocol/protocolVersion": tc.proto} } - got := c.send(tc.sid, tc.proto, map[string]any{"jsonrpc": "2.0", "id": 99, "method": m, "params": params}) + var extra map[string]string + if tc.meta { + extra = map[string]string{mcp.HeaderMethod: m} + } + got := c.sendWith(tc.sid, tc.proto, extra, map[string]any{"jsonrpc": "2.0", "id": 99, "method": m, "params": params}) assert.GreaterOrEqual(t, got.status, 400, "%s is refused: %s", m, got.body) + if code, ok := wantCode[tc.name]; ok { + require.NotNil(t, got.err, "%s: %s", m, got.body) + assert.Equal(t, code, got.err.Code, "%s: refused for the version: %s", m, got.body) + } if m == "tools/call" { want = got continue @@ -333,6 +365,8 @@ func openStream(t *testing.T, url, sid string) (closed <-chan struct{}, cancel f resp, err := http.DefaultClient.Do(req) require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) + require.True(t, strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream"), + "a listening stream: %s", resp.Header.Get("Content-Type")) done := make(chan struct{}) go func() { defer close(done) @@ -344,6 +378,11 @@ func openStream(t *testing.T, url, sid string) (closed <-chan struct{}, cancel f } } }() + select { + case <-done: + t.Fatalf("the stream closed by itself") + case <-time.After(300 * time.Millisecond): + } return done, stop } @@ -432,11 +471,17 @@ func TestNativeSkills_AcquireRacesRetire(t *testing.T) { } }() } + countAcquired := func() int { mu.Lock(); defer mu.Unlock(); return len(acquired) } + require.Eventually(t, func() bool { return countAcquired() > 0 }, 10*time.Second, time.Millisecond, + "the workers acquire before the toggling starts") on := true for i := 0; i < 40; i++ { on = !on g.commitGlobal(t, func(c *config.Config) { c.EnableSkills = on }) + before := countAcquired() g.p.retireStaleNativeSurfaces() + require.Eventually(t, func() bool { return countAcquired() > before }, 10*time.Second, time.Millisecond, + "acquisitions keep running between retirements") } close(stop) wg.Wait() @@ -445,6 +490,7 @@ func TestNativeSkills_AcquireRacesRetire(t *testing.T) { g.p.singleServersMu.Lock() live := g.p.singleServers[realSkillsSrv] g.p.singleServersMu.Unlock() + retiredSeen := 0 for _, ep := range acquired { if live != nil && ep.server == live.server { assert.Same(t, live.transport, ep.transport, "the live instance has exactly one transport") @@ -452,10 +498,12 @@ func TestNativeSkills_AcquireRacesRetire(t *testing.T) { } select { case <-ep.retired: + retiredSeen++ default: t.Fatalf("an acquired endpoint that is not live was never retired") } } + assert.Positive(t, retiredSeen, "endpoints were acquired and then retired") } // T050: an initialize that acquired its endpoint before a retirement answers @@ -464,11 +512,18 @@ func TestNativeSkills_PausedInitializeKeepsItsUpstream(t *testing.T) { g := newNativeSkills(t) url := g.singleURL() + // The upstream's own instructions reach a client of the endpoint. + plain := newRawMCP(t, url) + _, instr := plain.initialize() + require.Equal(t, nativeUpstreamInstructions, instr) + entered, release := make(chan struct{}), make(chan struct{}) - var once sync.Once + var pauseOnce, releaseOnce sync.Once + releaseAll := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(releaseAll) hook := func(string) { paused := false - once.Do(func() { paused = true }) + pauseOnce.Do(func() { paused = true }) if paused { close(entered) <-release @@ -478,28 +533,41 @@ func TestNativeSkills_PausedInitializeKeepsItsUpstream(t *testing.T) { t.Cleanup(func() { g.env.proxyServer.singleServerAcquired.Store(nil) }) type initOut struct { + ok bool caps map[string]any instructions string } out := make(chan initOut, 1) go func() { + res := initOut{} + // require in this goroutine ends it with Goexit: still report. + defer func() { out <- res }() c := newRawMCP(t, url) - caps, instr := c.initialize() - out <- initOut{caps, instr} + res.caps, res.instructions = c.initialize() + res.ok = true }() - <-entered + select { + case <-entered: + case <-time.After(30 * time.Second): + t.Fatal("the initialize never reached the endpoint") + } g.commitGlobal(t, func(c *config.Config) { c.EnableSkills = false }) g.p.RefreshSkillsAvailability() g.p.singleServersMu.Lock() _, cached := g.p.singleServers[realSkillsSrv] g.p.singleServersMu.Unlock() - require.False(t, cached, "the endpoint was retired while the initialize was paused") - close(release) - - got := <-out + assert.False(t, cached, "the endpoint was retired while the initialize was paused") + releaseAll() + + var got initOut + select { + case got = <-out: + case <-time.After(30 * time.Second): + t.Fatal("the paused initialize never answered") + } + require.True(t, got.ok, "the paused initialize failed") assert.True(t, hasSkillsExtension(got.caps), "served by the instance it acquired") - assert.NotContains(t, got.instructions, "retrieve_tools", "never the aggregate instructions") - assert.NotContains(t, got.instructions, "mcpproxy") + assert.Equal(t, nativeUpstreamInstructions, got.instructions, "the upstream's instructions, never the aggregate ones") } // An excluded server (expose_skills: false) does not announce the extension; diff --git a/internal/skills/skillstest/fixture.go b/internal/skills/skillstest/fixture.go index 000646870..81474be78 100644 --- a/internal/skills/skillstest/fixture.go +++ b/internal/skills/skillstest/fixture.go @@ -85,6 +85,8 @@ type Fixture struct { requests []Request failList bool delay time.Duration + // instructions is sent in the initialize result when not empty. + instructions string } // New starts the fixture and registers its shutdown with t. @@ -151,6 +153,14 @@ func (f *Fixture) SetListFailure(fail bool) { f.failList = fail } +// SetInstructions makes the initialize result carry instructions. Set it +// before the consumer connects. +func (f *Fixture) SetInstructions(text string) { + f.mu.Lock() + defer f.mu.Unlock() + f.instructions = text +} + // SetDelay makes every answer wait d first. func (f *Fixture) SetDelay(d time.Duration) { f.mu.Lock() @@ -302,11 +312,17 @@ func (f *Fixture) handle(w http.ResponseWriter, r *http.Request) { caps["extensions"] = map[string]any{skills.ExtensionKey: map[string]any{}} } w.Header().Set("Mcp-Session-Id", "skillstest-session") - writeResult(w, req.ID, map[string]any{ + result := map[string]any{ "protocolVersion": "2025-11-25", "capabilities": caps, "serverInfo": map[string]any{"name": "skillstest", "version": "1.0.0"}, - }) + } + f.mu.Lock() + if f.instructions != "" { + result["instructions"] = f.instructions + } + f.mu.Unlock() + writeResult(w, req.ID, result) case "tools/list": writeResult(w, req.ID, map[string]any{"tools": []any{map[string]any{ "name": "echo", From e34d39bb9c9707c0cfc78178c1cf38d7b1a3370b Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 13:47:48 +0200 Subject: [PATCH 5/8] Preserve transport validation and ordinary resource reads on native Skills endpoints --- docs/features/skills.md | 4 +- internal/server/skills_native.go | 425 +++++++++++++++++-- internal/server/skills_native_gate_test.go | 467 +++++++++++++++++++++ 3 files changed, 857 insertions(+), 39 deletions(-) create mode 100644 internal/server/skills_native_gate_test.go diff --git a/docs/features/skills.md b/docs/features/skills.md index 909d0d2a5..3738ab843 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -248,7 +248,9 @@ A held, changed, blocked or unusable skill is not listed, and asking for it by a The aggregated endpoints (`/mcp`, `/mcp/all`, `/mcp/code`, `/mcp/call`, `/mcp/p/`) never announce the extension. They offer the [skill tools](#agent-tools) instead. -**Same door as the tools.** A caller whose credential or profile does not reach the server gets the endpoint's `404`, exactly as for its tools. Each of the three requests is answered only after the endpoint's transport has accepted it the way it accepts a `tools/call`: a request without a session id, with a session id another endpoint issued, or with a protocol version the endpoint does not serve gets the same refusal a `tools/call` gets. +**Same door as the tools.** A caller whose credential or profile does not reach the server gets the endpoint's `404`, exactly as for its tools. Each of the three requests is answered only after the endpoint's transport has accepted it the way it accepts a `tools/call`: a request without a session id, with a session id another endpoint issued, or with a protocol version the endpoint does not serve gets the same refusal a `tools/call` gets. The single-server endpoint currently serves protocol revisions for which the transport ignores the `Mcp-Method` and `Mcp-Name` headers. + +**Ordinary resources stay ordinary.** Only `resources/read` of a skill address (`skill://…`, or a file address a skill of that server lists) is answered by the skills surface. Any other `resources/read` on the same endpoint goes to the endpoint's transport unchanged, gets the answer it gets without native skills, and is not recorded as a `skill_access`. **Following the switch.** Turning `enable_skills` on or off, or changing a server's `expose_skills`, retires that server's single-server endpoint: its open streams are closed and the session ids it issued are refused (`404`), so the client initializes again and sees the new capabilities. Nothing has to be restarted. diff --git a/internal/server/skills_native.go b/internal/server/skills_native.go index 361c49e7e..dc308ac91 100644 --- a/internal/server/skills_native.go +++ b/internal/server/skills_native.go @@ -9,6 +9,7 @@ import ( "net/http" "strings" "time" + "unicode" "github.com/mark3labs/mcp-go/mcp" mcpserver "github.com/mark3labs/mcp-go/server" @@ -35,8 +36,11 @@ import ( // answered by an interceptor in front of the instance's transport. Before it // answers, the request must pass every check the transport applies to a // tools/call: the interceptor sends the same request, with its method -// replaced by "ping", through the transport itself and answers only when the -// transport accepted it. A refusal (wrong content type, missing, foreign or +// replaced by "ping" ("server/discover" for a modern request, where ping was +// removed), through the transport itself and answers only when the transport +// accepted it. The Mcp-Method and Mcp-Name headers are checked first against +// the original method and params with the SDK's own rule, and a mismatch is +// answered as the SDK answers it, after the transport's earlier checks. A refusal (wrong content type, missing, foreign or // stale session id, unsupported protocol version, bad JSON-RPC version) is // the transport's own answer, passed on unchanged. The checks are therefore // the transport's, not a copy of them that could drift. @@ -89,13 +93,20 @@ type nativeSkillsRequest struct { ID json.RawMessage `json:"id"` Method string `json:"method"` Params json.RawMessage `json:"params"` + + raw []byte // the whole body, as received } // parseNativeSkillsRequest returns the request when body is one JSON-RPC // request (not a notification, not a batch) for one of the three methods. +// A body that repeats a member at the top level or directly in params is +// left to the transport: the SDK decodes repeats into struct fields (merging +// a repeated "params", stopping at a malformed "_meta" even when a later one +// is valid), while a raw read keeps only the last, so the two could disagree +// on the request's protocol era or params. func parseNativeSkillsRequest(body []byte) (*nativeSkillsRequest, bool) { trimmed := bytes.TrimSpace(body) - if len(trimmed) == 0 || trimmed[0] != '{' { + if len(trimmed) == 0 || trimmed[0] != '{' || hasRepeatedTopLevelMember(trimmed) { return nil, false } var req nativeSkillsRequest @@ -110,18 +121,129 @@ func parseNativeSkillsRequest(body []byte) (*nativeSkillsRequest, bool) { if id := bytes.TrimSpace(req.ID); len(id) == 0 || bytes.Equal(id, []byte("null")) { return nil, false } + if p := bytes.TrimSpace(req.Params); len(p) > 0 && p[0] == '{' && hasRepeatedTopLevelMember(p) { + return nil, false + } + req.raw = trimmed return &req, true } -// pingProbeBody is body with its method replaced by "ping"; everything else +// hasRepeatedTopLevelMember reports whether the JSON object obj names one of +// its members twice (or does not tokenize as an object). Names are compared +// the way encoding/json matches them to struct fields, case-insensitively, so +// "jsonrpc" and "JSONRPC" are the same member. +func hasRepeatedTopLevelMember(obj []byte) bool { + dec := json.NewDecoder(bytes.NewReader(obj)) + if tok, err := dec.Token(); err != nil || tok != json.Delim('{') { + return true + } + seen := map[string]bool{} + for dec.More() { + tok, err := dec.Token() + if err != nil { + return true + } + key, ok := tok.(string) + if !ok || seen[foldMemberName(key)] { + return true + } + seen[foldMemberName(key)] = true + var skip json.RawMessage + if err := dec.Decode(&skip); err != nil { + return true + } + } + return false +} + +// foldMemberName maps every rune to the smallest rune of its simple case +// folding orbit, so two names encoding/json would match to the same field +// (strings.EqualFold) map to the same key. +func foldMemberName(name string) string { + var b strings.Builder + b.Grow(len(name)) + for _, r := range name { + least := r + for f := unicode.SimpleFold(r); f != r; f = unicode.SimpleFold(f) { + if f < least { + least = f + } + } + b.WriteRune(least) + } + return b.String() +} + +// probeMeta is params._meta as the SDK decodes it (a struct field, matched +// case-insensitively, last occurrence wins because mcp.Meta replaces itself), +// when it decodes as mcp.Meta. +func probeMeta(params json.RawMessage) (json.RawMessage, bool) { + if t := bytes.TrimSpace(params); len(t) == 0 || t[0] != '{' { + return nil, false + } + var p struct { + Meta json.RawMessage `json:"_meta"` + } + if err := json.Unmarshal(params, &p); err != nil { + return nil, false + } + if t := bytes.TrimSpace(p.Meta); len(t) == 0 || bytes.Equal(t, []byte("null")) { + return nil, false + } + if err := json.Unmarshal(p.Meta, new(mcp.Meta)); err != nil { + return nil, false + } + return p.Meta, true +} + +// probeMethod is the side-effect-free method the probe carries: ping for the +// legacy era, server/discover for a request whose _meta names a modern +// protocol version (2026-07-28 removed ping; the SDK refuses it there). The +// era is read the way the SDK reads it, from params._meta. +func probeMethod(req *nativeSkillsRequest) mcp.MCPMethod { + var params struct { + Meta *mcp.Meta `json:"_meta"` + } + if len(req.Params) > 0 && json.Unmarshal(req.Params, ¶ms) == nil && + mcp.IsModernProtocol(params.Meta.ProtocolVersion()) { + return mcp.MethodServerDiscover + } + return mcp.MethodPing +} + +// probeBody is body with its method replaced by method; everything else // (jsonrpc, id, params with _meta) is kept, so the transport decides the era // and the checks exactly as it would for the real request. -func pingProbeBody(body []byte) ([]byte, error) { +func probeBody(body []byte, method mcp.MCPMethod) ([]byte, error) { var obj map[string]json.RawMessage if err := json.Unmarshal(body, &obj); err != nil { return nil, err } - obj["method"] = json.RawMessage(`"` + string(mcp.MethodPing) + `"`) + // Members are matched as encoding/json matches them (no name repeats, + // case-insensitively: parseNativeSkillsRequest refused any repeat). + var params json.RawMessage + for k, raw := range obj { + switch { + case strings.EqualFold(k, "method"): + delete(obj, k) + case strings.EqualFold(k, "params"): + params = raw + delete(obj, k) + } + } + obj["method"] = json.RawMessage(`"` + string(method) + `"`) + // The probe's params are the request's _meta and nothing else: _meta is + // all the transport's checks read (era, protocol version, client + // capabilities); the rest is the answer's to judge, not the probe + // method's parser. A _meta the SDK cannot decode makes the SDK read the + // request as legacy, as a probe without one is read. + if meta, ok := probeMeta(params); ok { + probeParams, err := json.Marshal(map[string]json.RawMessage{"_meta": meta}) + if err != nil { + return nil, err + } + obj["params"] = probeParams + } return json.Marshal(obj) } @@ -149,8 +271,8 @@ func (b *bufferedResponse) WriteHeader(code int) { } } -// accepted reports whether the transport answered the probe with a ping -// result: every check passed. +// accepted reports whether the transport answered the probe with a result: +// every check passed. func (b *bufferedResponse) accepted() bool { if b.status != http.StatusOK { return false @@ -165,6 +287,32 @@ func (b *bufferedResponse) accepted() bool { return len(msg.Result) > 0 && len(msg.Error) == 0 } +// refusedWith reports whether the recorded answer is a JSON-RPC error with +// code and message. +func (b *bufferedResponse) refusedWith(code int, message string) bool { + var msg struct { + Error *struct { + Code int `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal(b.body.Bytes(), &msg); err != nil || msg.Error == nil { + return false + } + return msg.Error.Code == code && msg.Error.Message == message +} + +// copyProbeHeaders passes on the headers the transport set on the probe's +// answer, except those of its body. +func copyProbeHeaders(w http.ResponseWriter, rec *bufferedResponse) { + for k, v := range rec.header { + if k == "Content-Length" || k == "Content-Type" { + continue + } + w.Header()[k] = v + } +} + // replay writes the recorded answer unchanged. func (b *bufferedResponse) replay(w http.ResponseWriter) { for k, v := range b.header { @@ -180,9 +328,131 @@ func (b *bufferedResponse) replay(w http.ResponseWriter) { // nativeSkillsInterceptor answers skills/list, skills/get and resources/read // on a single-server endpoint built with the native surface, after the -// transport (next) has accepted the request's ping probe. Every other request -// goes to next untouched. +// transport (next) has accepted the request's ping probe. Every other request, +// including a resources/read of an address that is not a skill's, goes to next +// untouched. func (p *MCPProxyServer) nativeSkillsInterceptor(ep *singleServerEndpoint, next http.Handler) http.Handler { + claims := func(req *nativeSkillsRequest) bool { + return nativeClaims(req, func(uri string) bool { return p.nativeKnowsFileURI(ep.name, uri) }) + } + answer := func(w http.ResponseWriter, r *http.Request, req *nativeSkillsRequest) { + p.answerNativeSkills(w, r, ep, req) + } + return nativeProbeGate(next, claims, answer) +} + +// nativeClaims reports whether the native surface answers req. skills/list +// and skills/get always (the SDK knows neither). A resources/read only when +// the SDK itself would parse it (mcp.ReadResourceRequest, so a request the +// SDK refuses as unparsable keeps the SDK's refusal) and its uri is a skill +// address (nativeReadIsSkillAddress). +func nativeClaims(req *nativeSkillsRequest, known func(string) bool) bool { + if req.Method != nativeMethodRead { + return true + } + var sdkReq mcp.ReadResourceRequest + if err := json.Unmarshal(req.raw, &sdkReq); err != nil { + return false + } + return nativeReadIsSkillAddress(sdkReq.Params.URI, known) +} + +// nativeReadIsSkillAddress decides which resources/read requests the native +// surface answers: an address in the extension's skill:// namespace, or one a +// skill of this server lists under another scheme (known). Every other read, +// one without a uri included, is an ordinary resource read and stays the +// transport's, answered exactly as on an endpoint without the native surface. +func nativeReadIsSkillAddress(uri string, known func(string) bool) bool { + if strings.HasPrefix(uri, skillScheme) { + return true + } + return uri != "" && known != nil && known(uri) +} + +// skillScheme is the extension's address namespace. +const skillScheme = "skill://" + +// nativeKnowsFileURI reports whether an available skill of server is listed +// under uri or lists a file under it. +func (p *MCPProxyServer) nativeKnowsFileURI(server, uri string) bool { + cat := p.skills() + if cat == nil { + return false + } + list, err := cat.ListAvailableSkills(server) + if err != nil { + return false + } + for _, sk := range list { + if sk.URI == uri { + return true + } + for _, f := range sk.Files { + if f.URI == uri { + return true + } + } + } + return false +} + +// nativeStandardHeaderError checks the request's Mcp-Method and Mcp-Name +// headers against its ORIGINAL method and params with the SDK's own rule +// (mcp.ValidateStandardHeaders), under the same conditions the SDK applies +// it: an HTTP request stating Mcp-Protocol-Version whose _meta names a modern +// protocol version. It runs before the probe rewrites anything, because the +// probe's method (ping) needs no Mcp-Name and would hide a mismatch. +func nativeStandardHeaderError(h http.Header, req *nativeSkillsRequest) error { + version, ok := modernHeaderVersion(h, req) + if !ok { + return nil + } + return mcp.ValidateStandardHeaders(h.Get, version, mcp.MCPMethod(req.Method), req.Params) +} + +// modernHeaderVersion is the protocol version the SDK checks the standard +// headers under, and whether it checks them at all: an HTTP request stating +// Mcp-Protocol-Version whose params._meta names a modern version. +func modernHeaderVersion(h http.Header, req *nativeSkillsRequest) (string, bool) { + if len(h) == 0 || h.Get(mcp.HeaderProtocolVersion) == "" { + return "", false + } + var params struct { + Meta *mcp.Meta `json:"_meta"` + } + if len(req.Params) > 0 { + if err := json.Unmarshal(req.Params, ¶ms); err != nil { + // The SDK reads such a request as legacy. + return "", false + } + } + version := params.Meta.ProtocolVersion() + return version, mcp.IsModernProtocol(version) +} + +// writeNativeHeaderMismatch answers a header mismatch the way the SDK does: +// a JSON-RPC error with HEADER_MISMATCH and the error's text, HTTP 400 (the +// status protocol version 2026-07-28 prescribes; only modern requests carry +// the headers, so only they reach this). +func writeNativeHeaderMismatch(w http.ResponseWriter, id json.RawMessage, err error) { + var rawID any + _ = json.Unmarshal(id, &rawID) + resp := mcp.JSONRPCError{ + JSONRPC: mcp.JSONRPC_VERSION, + ID: mcp.NewRequestId(rawID), + Error: mcp.NewJSONRPCErrorDetails(mcp.HEADER_MISMATCH, err.Error(), nil), + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _ = json.NewEncoder(w).Encode(resp) +} + +// nativeProbeGate is the transport-parity part of the interceptor: it hands +// every request it does not claim to next untouched, and answers a claimed one +// only after the SDK's checks passed, in the SDK's order (transport checks, +// then the standard headers against the original method). +func nativeProbeGate(next http.Handler, claims func(*nativeSkillsRequest) bool, + answer func(http.ResponseWriter, *http.Request, *nativeSkillsRequest)) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost || r.Body == nil { next.ServeHTTP(w, r) @@ -197,11 +467,15 @@ func (p *MCPProxyServer) nativeSkillsInterceptor(ep *singleServerEndpoint, next } r.Body = io.NopCloser(bytes.NewReader(body)) req, ok := parseNativeSkillsRequest(body) - if !ok { + if !ok || !claims(req) { next.ServeHTTP(w, r) return } - probe, err := pingProbeBody(body) + // Decided on the original request, before either the body or the + // headers are rewritten for the probe. + headerErr := nativeStandardHeaderError(r.Header, req) + method := probeMethod(req) + probe, err := probeBody(body, method) if err != nil { next.ServeHTTP(w, r) return @@ -210,25 +484,48 @@ func (p *MCPProxyServer) nativeSkillsInterceptor(ep *singleServerEndpoint, next pr.Body = io.NopCloser(bytes.NewReader(probe)) pr.ContentLength = int64(len(probe)) pr.Header = r.Header.Clone() - // A modern request must name its method in Mcp-Method; keep a header - // that agreed with the body agreeing with the probe, and leave a - // disagreeing one as it is so the transport refuses it. - if pr.Header.Get(mcp.HeaderMethod) == req.Method { - pr.Header.Set(mcp.HeaderMethod, string(mcp.MethodPing)) + // Mcp-Name, which neither probe method uses, is dropped. When the + // original headers agree, a stated Mcp-Method names the probe's + // method. When they do not, the probe is made to fail the SDK's same + // header check, at the same point (after the transport's earlier + // checks, before any hook runs): its Mcp-Method names the original + // method, or stays absent when the original omitted it. That refusal + // is then answered with the original request's own (headerErr). + pr.Header.Del(mcp.HeaderName) + var standIn string + if headerErr == nil { + if pr.Header.Get(mcp.HeaderMethod) != "" { + pr.Header.Set(mcp.HeaderMethod, string(method)) + } + } else { + if pr.Header.Get(mcp.HeaderMethod) != "" { + pr.Header.Set(mcp.HeaderMethod, req.Method) + } + if version, ok := modernHeaderVersion(r.Header, req); ok { + if err := mcp.ValidateStandardHeaders(pr.Header.Get, version, method, nil); err != nil { + standIn = err.Error() + } + } } rec := newBufferedResponse() next.ServeHTTP(rec, pr) if !rec.accepted() { + if headerErr != nil && standIn != "" && rec.refusedWith(mcp.HEADER_MISMATCH, standIn) { + copyProbeHeaders(w, rec) + writeNativeHeaderMismatch(w, req.ID, headerErr) + return + } rec.replay(w) return } - for k, v := range rec.header { - if k == "Content-Length" || k == "Content-Type" { - continue - } - w.Header()[k] = v + copyProbeHeaders(w, rec) + if headerErr != nil { + // Not reached while the SDK checks the probe's headers as it + // checks the request's; refused all the same. + writeNativeHeaderMismatch(w, req.ID, headerErr) + return } - p.answerNativeSkills(w, r, ep, req) + answer(w, r, req) }) } @@ -239,7 +536,7 @@ type nativeAnswer struct { msg string } -func writeNativeAnswer(w http.ResponseWriter, id json.RawMessage, a nativeAnswer) { +func writeNativeAnswer(w http.ResponseWriter, id json.RawMessage, modern bool, a nativeAnswer) { out := map[string]any{"jsonrpc": mcp.JSONRPC_VERSION, "id": id} if a.code != 0 { out["error"] = map[string]any{"code": a.code, "message": a.msg} @@ -247,10 +544,30 @@ func writeNativeAnswer(w http.ResponseWriter, id json.RawMessage, a nativeAnswer out["result"] = a.result } w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) + w.WriteHeader(nativeAnswerStatus(modern, a.code)) _ = json.NewEncoder(w).Encode(out) } +// nativeAnswerStatus is the HTTP status the SDK's transport sends a JSON-RPC +// answer with: 200 for the legacy era; for a modern request (the probe passed, +// so header and _meta agree on the version) the status protocol version +// 2026-07-28 maps the error code to. The SDK's mapping is unexported; this +// copy is pinned to it by TestNativeProbeGate_AnswerStatusMatchesSDK. +func nativeAnswerStatus(modern bool, code int) int { + if !modern { + return http.StatusOK + } + switch code { + case mcp.METHOD_NOT_FOUND: + return http.StatusNotFound + case mcp.HEADER_MISMATCH, mcp.MISSING_REQUIRED_CLIENT_CAPABILITY, mcp.UNSUPPORTED_PROTOCOL_VERSION, + mcp.INVALID_REQUEST, mcp.INVALID_PARAMS, mcp.PARSE_ERROR: + return http.StatusBadRequest + default: + return http.StatusOK + } +} + // nativeSkillEntry is one entry of the extension's listing. type nativeSkillEntry struct { URI string `json:"uri"` @@ -345,29 +662,61 @@ func (p *MCPProxyServer) answerNativeSkills(w http.ResponseWriter, r *http.Reque a := p.nativeSkillsAnswer(ctx, ep, req, &act) act.DurationMs = time.Since(start).Milliseconds() p.emitSkillAccess(ctx, act) - writeNativeAnswer(w, req.ID, a) + writeNativeAnswer(w, req.ID, mcp.IsModernProtocol(r.Header.Get(mcp.HeaderProtocolVersion)), a) } -func (p *MCPProxyServer) nativeSkillsAnswer(ctx context.Context, ep *singleServerEndpoint, req *nativeSkillsRequest, act *runtime.SkillAccessActivity) nativeAnswer { - var params struct { - Cursor *string `json:"cursor"` - URI *string `json:"uri"` +// nativeParams decodes the params each method reads, and only those: a +// member another method uses is ignored, as the SDK ignores members its params +// type does not name. resources/read is decoded with the SDK's own type +// (nativeClaims admitted only reads that parse with it); skills/list reads +// cursor and skills/get reads uri, each with _meta decoded so a malformed one +// is invalid params. ok is false when params do not decode. +func nativeParams(req *nativeSkillsRequest) (cursor, uri string, ok bool) { + t := bytes.TrimSpace(req.Params) + if len(t) == 0 || bytes.Equal(t, []byte("null")) { + return "", "", true } - if len(bytes.TrimSpace(req.Params)) > 0 && !bytes.Equal(bytes.TrimSpace(req.Params), []byte("null")) { - if err := json.Unmarshal(req.Params, ¶ms); err != nil { - act.Outcome = runtime.SkillAccessInvalid - return nativeAnswer{code: mcp.INVALID_PARAMS, msg: "invalid params"} + switch req.Method { + case nativeMethodRead: + var p mcp.ReadResourceParams + if err := json.Unmarshal(req.Params, &p); err != nil { + return "", "", false } + return "", p.URI, true + case nativeMethodGet: + var p struct { + URI string `json:"uri"` + Meta *mcp.Meta `json:"_meta"` + } + if err := json.Unmarshal(req.Params, &p); err != nil { + return "", "", false + } + return "", p.URI, true + default: + var p struct { + Cursor string `json:"cursor"` + Meta *mcp.Meta `json:"_meta"` + } + if err := json.Unmarshal(req.Params, &p); err != nil { + return "", "", false + } + return p.Cursor, "", true + } +} + +func (p *MCPProxyServer) nativeSkillsAnswer(ctx context.Context, ep *singleServerEndpoint, req *nativeSkillsRequest, act *runtime.SkillAccessActivity) nativeAnswer { + cursor, uri, ok := nativeParams(req) + if !ok { + act.Outcome = runtime.SkillAccessInvalid + return nativeAnswer{code: mcp.INVALID_PARAMS, msg: "invalid params"} } - uri := "" if req.Method != nativeMethodList { - if params.URI == nil || *params.URI == "" { + if uri == "" { act.Outcome = runtime.SkillAccessInvalid return nativeAnswer{code: mcp.INVALID_PARAMS, msg: "missing required parameter: uri"} } - uri = *params.URI act.SkillID = cutRunes(echoSkillID(uri), skillIDEchoMax) - } else if params.Cursor != nil && *params.Cursor != "" { + } else if cursor != "" { // The whole listing is one page; no cursor was ever issued. act.Outcome = runtime.SkillAccessInvalid return nativeAnswer{code: mcp.INVALID_PARAMS, msg: "invalid cursor"} diff --git a/internal/server/skills_native_gate_test.go b/internal/server/skills_native_gate_test.go new file mode 100644 index 000000000..49b53c87d --- /dev/null +++ b/internal/server/skills_native_gate_test.go @@ -0,0 +1,467 @@ +package server + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/mark3labs/mcp-go/mcp" + mcpserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// Spec 125 PR-5 review follow-up: the native probe gate against a bare mcp-go +// transport that serves the modern protocol (mcpproxy pins it off today, so +// these checks are not reachable through the real endpoint yet). The gate's +// answer for every refusal must be the bare transport's own answer to the +// same request, byte for byte, and every read it does not claim must reach +// the transport unchanged. + +const gateOrdinaryURI = "file:///ordinary.txt" + +// gateFixture is a bare SDK instance with the native options, one tool, one +// ordinary resource and one ordinary template, served with and without the +// gate. +type gateFixture struct { + bare http.Handler + gated http.Handler + answered atomic.Int32 + hooks atomic.Int32 // OnBeforeAny calls: a request the SDK refused early runs none +} + +func newGateFixture(t *testing.T, known func(string) bool) *gateFixture { + t.Helper() + f := &gateFixture{} + hooks := &mcpserver.Hooks{} + hooks.AddBeforeAny(func(context.Context, any, mcp.MCPMethod, any) { f.hooks.Add(1) }) + srv := mcpserver.NewMCPServer("gate-test", "1", append(nativeSkillsServerOptions(), mcpserver.WithHooks(hooks))...) + srv.AddTool(mcp.NewTool("echo"), func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) { + return mcp.NewToolResultText("ok"), nil + }) + srv.AddResource(mcp.NewResource(gateOrdinaryURI, "ordinary"), func(context.Context, mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) { + return []mcp.ResourceContents{mcp.TextResourceContents{URI: gateOrdinaryURI, Text: "ORDINARY"}}, nil + }) + srv.AddResourceTemplate(mcp.NewResourceTemplate("ui://widget/{id}", "widget"), func(_ context.Context, r mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) { + return []mcp.ResourceContents{mcp.TextResourceContents{URI: r.Params.URI, Text: "WIDGET"}}, nil + }) + f.bare = mcpserver.NewStreamableHTTPServer(srv, mcpserver.WithStateLess(true)) + claims := func(req *nativeSkillsRequest) bool { return nativeClaims(req, known) } + f.gated = nativeProbeGate(f.bare, claims, func(w http.ResponseWriter, _ *http.Request, req *nativeSkillsRequest) { + f.answered.Add(1) + writeNativeAnswer(w, req.ID, true, nativeAnswer{result: map[string]any{"native": true}}) + }) + return f +} + +type gateReply struct { + status int + body string + err *rawRPCError +} + +func gateDo(t *testing.T, h http.Handler, method string, params map[string]any, headers map[string]string) gateReply { + t.Helper() + body, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 7, "method": method, "params": params}) + require.NoError(t, err) + return gateDoRaw(t, h, string(body), headers) +} + +func gateDoRaw(t *testing.T, h http.Handler, body string, headers map[string]string) gateReply { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/mcp/s/x", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + for k, v := range headers { + if v == "" { + req.Header.Del(k) + continue + } + req.Header.Set(k, v) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + raw, err := io.ReadAll(rec.Result().Body) + require.NoError(t, err) + out := gateReply{status: rec.Code, body: string(raw)} + var msg struct { + Error *rawRPCError `json:"error"` + } + if json.Unmarshal(raw, &msg) == nil { + out.err = msg.Error + } + return out +} + +// modernParams adds the modern-era _meta to params. +func modernParams(params map[string]any) map[string]any { + out := map[string]any{"_meta": map[string]any{ + mcp.MetaKeyProtocolVersion: mcp.ProtocolVersion20260728, + mcp.MetaKeyClientCapabilities: map[string]any{}, + }} + for k, v := range params { + out[k] = v + } + return out +} + +// modernHeaders are the headers a correct modern client sends for method and +// params (the SDK's own StandardHeaders), with overrides ("" deletes). +func modernHeaders(t *testing.T, method string, params map[string]any, override map[string]string) map[string]string { + t.Helper() + raw, err := json.Marshal(params) + require.NoError(t, err) + h := map[string]string{mcp.HeaderProtocolVersion: mcp.ProtocolVersion20260728} + for k, v := range mcp.StandardHeaders(mcp.ProtocolVersion20260728, mcp.MCPMethod(method), raw) { + h[k] = v + } + for k, v := range override { + h[k] = v + } + return h +} + +// The original Mcp-Method and Mcp-Name are validated against the original +// method and params, and the refusal is the SDK's own, unchanged. +func TestNativeProbeGate_StandardHeadersMatchTheSDK(t *testing.T) { + f := newGateFixture(t, nil) + const skillURI = "skill://pdf/SKILL.md" + methods := map[string]map[string]any{ + nativeMethodList: {}, + nativeMethodGet: {"uri": skillURI}, + nativeMethodRead: {"uri": skillURI}, + } + cases := []struct { + name string + override map[string]string + only string // method the case applies to; "" = all + }{ + {"Mcp-Method names another method", map[string]string{mcp.HeaderMethod: "tools/list"}, ""}, + {"Mcp-Method names ping", map[string]string{mcp.HeaderMethod: string(mcp.MethodPing)}, ""}, + {"Mcp-Method missing", map[string]string{mcp.HeaderMethod: ""}, ""}, + {"Mcp-Name names another resource", map[string]string{mcp.HeaderName: "skill://other/SKILL.md"}, nativeMethodRead}, + {"Mcp-Name missing", map[string]string{mcp.HeaderName: ""}, nativeMethodRead}, + {"Mcp-Name not valid base64", map[string]string{mcp.HeaderName: "=?base64?***?="}, nativeMethodRead}, + } + for _, tc := range cases { + for method, p := range methods { + if tc.only != "" && tc.only != method { + continue + } + t.Run(tc.name+"/"+method, func(t *testing.T) { + params := modernParams(p) + h := modernHeaders(t, method, params, tc.override) + want := gateDo(t, f.bare, method, params, h) + require.NotNil(t, want.err, "the SDK refuses: %s", want.body) + require.Equal(t, mcp.HEADER_MISMATCH, want.err.Code, want.body) + + before, hooksBefore := f.answered.Load(), f.hooks.Load() + got := gateDo(t, f.gated, method, params, h) + assert.Equal(t, before, f.answered.Load(), "a header mismatch is never answered natively") + assert.Equal(t, hooksBefore, f.hooks.Load(), "refused before any hook runs, as the SDK refuses it") + assert.Equal(t, want.status, got.status, "status like the SDK: %s", got.body) + assert.Equal(t, want.body, got.body, "the SDK's refusal, unchanged") + assert.NotContains(t, got.body, `"ping"`, "the probe's method never shows") + assert.NotContains(t, got.body, string(mcp.MethodServerDiscover), "the probe's method never shows") + }) + } + } + + // Agreeing headers pass. + for method, p := range methods { + params := modernParams(p) + before := f.answered.Load() + got := gateDo(t, f.gated, method, params, modernHeaders(t, method, params, nil)) + assert.Equal(t, http.StatusOK, got.status, "%s: %s", method, got.body) + assert.Nil(t, got.err, got.body) + assert.Equal(t, before+1, f.answered.Load(), "%s is answered natively", method) + } +} + +// The transport's earlier checks still come first: a request refused for its +// protocol version is refused for that, even when its headers also disagree. +func TestNativeProbeGate_TransportChecksComeBeforeHeaders(t *testing.T) { + f := newGateFixture(t, nil) + params := modernParams(map[string]any{"uri": "skill://pdf/SKILL.md"}) + h := modernHeaders(t, nativeMethodRead, params, map[string]string{ + mcp.HeaderProtocolVersion: "2025-06-18", // disagrees with _meta + mcp.HeaderMethod: "tools/list", + }) + want := gateDo(t, f.bare, nativeMethodRead, params, h) + got := gateDo(t, f.gated, nativeMethodRead, params, h) + require.NotNil(t, want.err, want.body) + assert.Equal(t, want.status, got.status) + assert.Equal(t, want.body, got.body) + assert.Zero(t, f.answered.Load()) +} + +// Ordinary resource reads on the same endpoint are the transport's: a +// registered resource, a template match and an unknown non-skill address all +// get exactly the answer the endpoint gives without the native surface. +func TestNativeProbeGate_OrdinaryResourceReadsStayTheSDKs(t *testing.T) { + const otherSchemeSkill = "file:///skills/pdf/SKILL.md" + f := newGateFixture(t, func(uri string) bool { return uri == otherSchemeSkill }) + for _, uri := range []string{gateOrdinaryURI, "ui://widget/42", "https://example.com/not-a-skill"} { + t.Run(uri, func(t *testing.T) { + params := modernParams(map[string]any{"uri": uri}) + h := modernHeaders(t, nativeMethodRead, params, nil) + want := gateDo(t, f.bare, nativeMethodRead, params, h) + got := gateDo(t, f.gated, nativeMethodRead, params, h) + assert.Equal(t, want.status, got.status) + assert.Equal(t, want.body, got.body, "the transport's own answer") + assert.Zero(t, f.answered.Load(), "never answered natively") + }) + } + // An address a skill of this server lists under another scheme is still + // the native surface's. + params := modernParams(map[string]any{"uri": otherSchemeSkill}) + got := gateDo(t, f.gated, nativeMethodRead, params, modernHeaders(t, nativeMethodRead, params, nil)) + assert.Nil(t, got.err, got.body) + assert.Equal(t, int32(1), f.answered.Load()) +} + +// Requests the SDK would refuse before or while parsing them keep the SDK's +// refusal: nothing the interceptor reads differently from the SDK can turn a +// refused request into a native answer. +func TestNativeProbeGate_RequestsTheSDKRefusesStayRefused(t *testing.T) { + f := newGateFixture(t, nil) + modernMeta := `"_meta":{"` + mcp.MetaKeyProtocolVersion + `":"` + mcp.ProtocolVersion20260728 + `","` + mcp.MetaKeyClientCapabilities + `":{}}` + cases := []struct { + name, body string + headers map[string]string + }{ + // The SDK merges repeated "params" objects, so it sees the modern + // _meta of the first and refuses the request for the missing + // Mcp-Protocol-Version header; a last-wins read would see a legacy + // request and serve it. + {"repeated params hides the modern era", `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{` + modernMeta + `},"params":{"uri":"skill://pdf/SKILL.md"}}`, nil}, + {"repeated params on skills/get", `{"jsonrpc":"2.0","id":7,"method":"skills/get","params":{` + modernMeta + `},"params":{"uri":"skill://pdf/SKILL.md"}}`, nil}, + {"repeated _meta, malformed first", `{"jsonrpc":"2.0","id":7,"method":"skills/list","params":{"_meta":[],` + modernMeta + `}}`, nil}, + {"repeated uri in params", `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{"uri":"skill://pdf/SKILL.md","URI":5}}`, nil}, + {"repeated method", `{"jsonrpc":"2.0","id":7,"method":"tools/list","method":"skills/list","params":{}}`, nil}, + // encoding/json matches member names case-insensitively: the SDK + // reads the last "JSONRPC" and refuses the version. + {"case-variant jsonrpc", `{"jsonrpc":"2.0","JSONRPC":"1.0","id":7,"method":"resources/read","params":{"uri":"skill://pdf/SKILL.md"}}`, nil}, + {"case-variant params", `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{` + modernMeta + `},"Params":{"uri":"skill://pdf/SKILL.md"}}`, nil}, + // ReadResourceParams.Arguments must be an object. + {"legacy read with non-object arguments", `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{"uri":"skill://pdf/SKILL.md","arguments":5}}`, nil}, + {"modern read with non-object arguments", `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{` + modernMeta + `,"uri":"skill://pdf/SKILL.md","arguments":5}}`, + map[string]string{mcp.HeaderProtocolVersion: mcp.ProtocolVersion20260728, mcp.HeaderMethod: nativeMethodRead, mcp.HeaderName: "skill://pdf/SKILL.md"}}, + {"read with array params", `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":[]}`, nil}, + {"read with uri of the wrong type", `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{"uri":5}}`, nil}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + want := gateDoRaw(t, f.bare, tc.body, tc.headers) + require.NotNil(t, want.err, "the SDK refuses: %s", want.body) + before := f.answered.Load() + got := gateDoRaw(t, f.gated, tc.body, tc.headers) + assert.Equal(t, before, f.answered.Load(), "never answered natively") + assert.Equal(t, want.status, got.status) + assert.Equal(t, want.body, got.body, "the SDK's refusal, unchanged") + }) + } + + // A read without a uri is not a skill read: the SDK's answer. + for _, body := range []string{ + `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{}}`, + `{"jsonrpc":"2.0","id":7,"method":"resources/read"}`, + `{"jsonrpc":"2.0","id":7,"method":"resources/read","params":{"uri":""}}`, + } { + want := gateDoRaw(t, f.bare, body, nil) + got := gateDoRaw(t, f.gated, body, nil) + assert.Equal(t, want.body, got.body, body) + } + assert.Zero(t, f.answered.Load()) + + // skills/* with params that are not an object: the probe carries no + // params, so the request reaches the answer (which refuses them, see + // TestNativeSkills_NonObjectParamsAreInvalidParams) and the probe's + // method never shows. + for _, m := range []string{nativeMethodList, nativeMethodGet} { + got := gateDoRaw(t, f.gated, `{"jsonrpc":"2.0","id":7,"method":"`+m+`","params":[]}`, nil) + assert.Equal(t, int32(1), f.answered.Load(), "%s reaches the answer: %s", m, got.body) + assert.NotContains(t, got.body, "ping", got.body) + f.answered.Store(0) + } +} + +// The probe carries the request's _meta and nothing else, so its own parser +// never judges the request's params. +func TestProbeBody_CarriesOnlyTheMeta(t *testing.T) { + meta := `{"` + mcp.MetaKeyProtocolVersion + `":"` + mcp.ProtocolVersion20260728 + `"}` + for in, want := range map[string]string{ + `{"jsonrpc":"2.0","id":1,"method":"skills/list","params":{"_meta":` + meta + `,"cursor":5}}`: `{"id":1,"jsonrpc":"2.0","method":"ping","params":{"_meta":` + meta + `}}`, + `{"jsonrpc":"2.0","id":1,"method":"skills/list","params":{"_META":` + meta + `}}`: `{"id":1,"jsonrpc":"2.0","method":"ping","params":{"_meta":` + meta + `}}`, + `{"jsonrpc":"2.0","id":1,"method":"skills/list","params":{"_meta":[]}}`: `{"id":1,"jsonrpc":"2.0","method":"ping"}`, + `{"jsonrpc":"2.0","id":1,"method":"skills/list","params":{"_meta":null,"uri":"x"}}`: `{"id":1,"jsonrpc":"2.0","method":"ping"}`, + `{"jsonrpc":"2.0","id":1,"method":"skills/list","params":[]}`: `{"id":1,"jsonrpc":"2.0","method":"ping"}`, + `{"jsonrpc":"2.0","id":1,"Method":"skills/list"}`: `{"id":1,"jsonrpc":"2.0","method":"ping"}`, + } { + got, err := probeBody([]byte(in), mcp.MethodPing) + require.NoError(t, err) + assert.JSONEq(t, want, string(got), in) + } +} + +func TestHasRepeatedTopLevelMember(t *testing.T) { + for body, want := range map[string]bool{ + `{"a":1,"b":{"a":1,"a":2}}`: false, // nested repeats are the params' own, passed verbatim + `{"a":1,"a":2}`: true, + `{"jsonrpc":1,"JSONRPC":2}`: true, + `{"k":1,"\u212a":2}`: true, // KELVIN SIGN folds to k + `{"ab":1,"ba":2}`: false, + `{"a":1,"b":[1,{"c":2}]}`: false, + `{"a":`: true, + `[]`: true, + } { + assert.Equal(t, want, hasRepeatedTopLevelMember([]byte(body)), body) + } +} + +func TestNativeReadIsSkillAddress(t *testing.T) { + known := func(uri string) bool { return uri == "file:///s/SKILL.md" } + for uri, want := range map[string]bool{ + "skill://pdf/SKILL.md": true, + "skill://pdf/scripts/x.py": true, + "skill://pdf/nope.md": true, // the extension's namespace: not found is ours to say + "": false, + "file:///s/SKILL.md": true, + "file:///ordinary.txt": false, + "ui://widget/1": false, + "skill:/pdf/SKILL.md": false, + "SKILL://pdf/SKILL.md": false, + "https://x.test/skill://pd": false, + } { + assert.Equal(t, want, nativeReadIsSkillAddress(uri, known), uri) + } + assert.False(t, nativeReadIsSkillAddress("file:///s/SKILL.md", nil)) +} + +// The copy of the SDK's status mapping answers what the SDK's transport sends +// for the same JSON-RPC error code. +func TestNativeProbeGate_AnswerStatusMatchesSDK(t *testing.T) { + f := newGateFixture(t, nil) + cases := []struct { + method string + params map[string]any + }{ + {"no/such/method", map[string]any{}}, // METHOD_NOT_FOUND + {string(mcp.MethodToolsCall), map[string]any{"name": "missing"}}, // tool not found + {string(mcp.MethodResourcesRead), map[string]any{"uri": "x://n"}}, // resource not found + {string(mcp.MethodToolsCall), map[string]any{"name": 5}}, // unparsable + } + seen := 0 + for _, tc := range cases { + params := modernParams(tc.params) + h := modernHeaders(t, tc.method, params, nil) + if tc.method == string(mcp.MethodToolsCall) { + if _, ok := tc.params["name"].(string); !ok { + h[mcp.HeaderName] = "5" + } + } + r := gateDo(t, f.bare, tc.method, params, h) + if r.err == nil { + continue + } + seen++ + assert.Equal(t, r.status, nativeAnswerStatus(true, r.err.Code), "%s: code %d", tc.method, r.err.Code) + assert.Equal(t, http.StatusOK, nativeAnswerStatus(false, r.err.Code)) + } + require.GreaterOrEqual(t, seen, 3, "the table exercised the SDK's mapping") + for _, code := range []int{mcp.INVALID_PARAMS, mcp.HEADER_MISMATCH} { + assert.Equal(t, http.StatusBadRequest, nativeAnswerStatus(true, code)) + } + assert.Equal(t, http.StatusOK, nativeAnswerStatus(true, nativeNotFoundCode)) + assert.Equal(t, http.StatusOK, nativeAnswerStatus(true, 0)) +} + +// Through the real endpoint (legacy era): an ordinary resources/read is not a +// skill access. It gets the transport's answer and records no skill row. +func TestNativeSkills_OrdinaryResourceReadIsNotASkillAccess(t *testing.T) { + g := newNativeSkills(t) + c := newRawMCP(t, g.singleURL()) + caps, _ := c.initialize() + require.True(t, hasSkillsExtension(caps)) + + for _, params := range []map[string]any{ + {"uri": "file:///etc/hosts"}, {"uri": "https://example.com/x"}, {"uri": "ui://widget/1"}, {}, + } { + r := c.call(nativeMethodRead, params) + require.NotNil(t, r.err, string(r.body)) + assert.Contains(t, r.err.Message, "handler not found for resource URI", "the SDK's own answer: %s", r.body) + assert.NotContains(t, r.err.Message, "resource not found: ", "not the native answer") + } + r0 := c.call(nativeMethodRead, map[string]any{"uri": "skill://pdf/SKILL.md", "arguments": 5}) + require.NotNil(t, r0.err, string(r0.body)) + assert.Equal(t, mcp.INVALID_REQUEST, r0.err.Code, "the SDK refuses what it cannot parse: %s", r0.body) + // A skill read on the same session is still native and recorded. + r := c.call(nativeMethodRead, map[string]any{"uri": "skill://pdf/SKILL.md"}) + require.Nil(t, r.err, string(r.body)) + + var rows []*storage.ActivityRecord + require.Eventually(t, func() bool { rows = g.nativeRows(t); return len(rows) >= 1 }, 10*time.Second, 50*time.Millisecond) + time.Sleep(200 * time.Millisecond) + rows = g.nativeRows(t) + require.Len(t, rows, 1, "only the skill read is a skill access") + assert.Equal(t, "success", rows[0].Metadata["outcome"]) +} + +// Through the real endpoint: skills/* with params that are not an object are +// refused by the native answer as invalid params, and a resources/read that +// repeats uri is left to the SDK. +func TestNativeSkills_NonObjectParamsAndRepeatedURI(t *testing.T) { + g := newNativeSkills(t) + c := newRawMCP(t, g.singleURL()) + c.initialize() + for _, m := range []string{nativeMethodList, nativeMethodGet} { + for _, params := range []any{ + []any{}, + map[string]any{"_meta": []any{}, "uri": "skill://pdf/SKILL.md"}, + map[string]any{"_meta": "x", "uri": "skill://pdf/SKILL.md"}, + } { + r := c.sendWith(c.sid, mcp.LATEST_LEGACY_PROTOCOL_VERSION, nil, map[string]any{"jsonrpc": "2.0", "id": c.nextID(), "method": m, "params": params}) + require.NotNil(t, r.err, "%s %v: %s", m, params, r.body) + assert.Equal(t, mcp.INVALID_PARAMS, r.err.Code, "%s %v: %s", m, params, r.body) + assert.NotContains(t, string(r.body), "ping") + } + } + // A member another method uses is ignored, as the SDK ignores it. + rc := c.call(nativeMethodRead, map[string]any{"uri": "skill://pdf/SKILL.md", "cursor": 5}) + require.Nil(t, rc.err, "a read ignores cursor: %s", rc.body) + rg := c.call(nativeMethodGet, map[string]any{"uri": "skill://pdf/SKILL.md", "cursor": 5}) + require.Nil(t, rg.err, "skills/get ignores cursor: %s", rg.body) + rl := c.call(nativeMethodList, map[string]any{"uri": 5}) + require.Nil(t, rl.err, "skills/list ignores uri: %s", rl.body) + + // resources/read with a malformed _meta is the SDK's to refuse. + r := c.call(nativeMethodRead, map[string]any{"_meta": []any{}, "uri": "skill://pdf/SKILL.md"}) + require.NotNil(t, r.err, string(r.body)) + assert.Equal(t, mcp.INVALID_REQUEST, r.err.Code, string(r.body)) + assert.Contains(t, r.err.Message, "unparsable resources/read request", string(r.body)) + + body := `{"jsonrpc":"2.0","id":901,"method":"resources/read","params":{"uri":"skill://pdf/SKILL.md","uri":null}}` + req, err := http.NewRequest(http.MethodPost, c.url, strings.NewReader(body)) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("Mcp-Session-Id", c.sid) + req.Header.Set("Mcp-Protocol-Version", mcp.LATEST_LEGACY_PROTOCOL_VERSION) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer resp.Body.Close() + raw, err := io.ReadAll(resp.Body) + require.NoError(t, err) + // A repeated member in params is the transport's: an ordinary read, the + // SDK's own answer, never a native one. + assert.Contains(t, string(raw), "handler not found for resource URI", "the SDK's answer: %s", raw) + assert.NotContains(t, string(raw), "missing required parameter") +} From c99660c50421372fd24b5ae65b4a541876d786f4 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 14:47:12 +0200 Subject: [PATCH 6/8] Regenerate roadmap after integrating current specifications --- ROADMAP.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 616504563..b9315cc74 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1208,3 +1208,6 @@ Legend: `shipped` ≥95% checked · `in-flight` 1–94% · `drafted` 0% · `—` | [123-oauth-token-encryption](./specs/123-oauth-token-encryption/) | `drafted` | 0/56 (0%) | | [124-session-failure-timeline](./specs/124-session-failure-timeline/) | `drafted` | 0/74 (0%) | | [125-skills-over-mcp](./specs/125-skills-over-mcp/) | `in-flight` | 46/51 (90%) | +| [127-profile-argument-rules](./specs/127-profile-argument-rules/) | — | — | +| [128-server-list-outcomes](./specs/128-server-list-outcomes/) | — | — | +| [129-per-user-upstream-credentials](./specs/129-per-user-upstream-credentials/) | — | — | From 303fa3144aa09667d221f511f88870e8c5e04d8f Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 20 Nov 2026 15:15:54 +0200 Subject: [PATCH 7/8] test(skills): check native response cleanup errors --- internal/server/skills_native_gate_test.go | 2 +- internal/server/skills_native_test.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/server/skills_native_gate_test.go b/internal/server/skills_native_gate_test.go index 49b53c87d..decc4fbff 100644 --- a/internal/server/skills_native_gate_test.go +++ b/internal/server/skills_native_gate_test.go @@ -457,7 +457,7 @@ func TestNativeSkills_NonObjectParamsAndRepeatedURI(t *testing.T) { req.Header.Set("Mcp-Protocol-Version", mcp.LATEST_LEGACY_PROTOCOL_VERSION) resp, err := http.DefaultClient.Do(req) require.NoError(t, err) - defer resp.Body.Close() + defer func() { assert.NoError(t, resp.Body.Close()) }() raw, err := io.ReadAll(resp.Body) require.NoError(t, err) // A repeated member in params is the transport's: an ordinary read, the diff --git a/internal/server/skills_native_test.go b/internal/server/skills_native_test.go index d8db987af..ac05bbdc2 100644 --- a/internal/server/skills_native_test.go +++ b/internal/server/skills_native_test.go @@ -80,7 +80,7 @@ func (c *rawMCP) sendWith(sid, proto string, extra map[string]string, msg map[st } resp, err := http.DefaultClient.Do(req) require.NoError(c.t, err) - defer resp.Body.Close() + defer func() { assert.NoError(c.t, resp.Body.Close()) }() raw, err := io.ReadAll(resp.Body) require.NoError(c.t, err) out := rawReply{status: resp.StatusCode, header: resp.Header, body: raw} @@ -370,7 +370,7 @@ func openStream(t *testing.T, url, sid string) (closed <-chan struct{}, cancel f done := make(chan struct{}) go func() { defer close(done) - defer resp.Body.Close() + defer func() { assert.NoError(t, resp.Body.Close()) }() r := bufio.NewReader(resp.Body) for { if _, err := r.ReadString('\n'); err != nil { From 0733283c17f9721fe6958b9f4dc514f0e2446017 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Sat, 21 Nov 2026 06:22:50 +0200 Subject: [PATCH 8/8] fix: harden intent errors and auth metadata allocation --- internal/contracts/intent.go | 2 +- internal/contracts/intent_test.go | 9 +++++++++ internal/server/mcp.go | 2 +- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/internal/contracts/intent.go b/internal/contracts/intent.go index eba5f2cdf..ea69f35a7 100644 --- a/internal/contracts/intent.go +++ b/internal/contracts/intent.go @@ -113,7 +113,7 @@ func (i *IntentDeclaration) Validate() *IntentValidationError { if i.DataSensitivity != "" && !isValidDataSensitivity(i.DataSensitivity) { return NewIntentValidationError( IntentErrorCodeInvalidSensitivity, - fmt.Sprintf("Invalid intent.data_sensitivity '%s': must be public, internal, private, or unknown", i.DataSensitivity), + "Invalid intent.data_sensitivity: must be public, internal, private, or unknown", map[string]interface{}{ "provided": i.DataSensitivity, "valid_values": ValidDataSensitivities, diff --git a/internal/contracts/intent_test.go b/internal/contracts/intent_test.go index 49be90490..546a37c00 100644 --- a/internal/contracts/intent_test.go +++ b/internal/contracts/intent_test.go @@ -197,6 +197,15 @@ func TestIntentDeclaration_Validate(t *testing.T) { if tt.wantErr && err != nil && err.Code != tt.wantErrCode { t.Errorf("Validate() error code = %v, wantErrCode %v", err.Code, tt.wantErrCode) } + if err != nil && tt.wantErrCode == IntentErrorCodeInvalidSensitivity { + const wantMessage = "Invalid intent.data_sensitivity: must be public, internal, private, or unknown" + if err.Message != wantMessage { + t.Errorf("Validate() error message = %q, want %q", err.Message, wantMessage) + } + if got := err.Details["provided"]; got != tt.intent.DataSensitivity { + t.Errorf("Validate() provided sensitivity = %q, want %q", got, tt.intent.DataSensitivity) + } + } }) } } diff --git a/internal/server/mcp.go b/internal/server/mcp.go index 8e5fb62bc..447afebed 100644 --- a/internal/server/mcp.go +++ b/internal/server/mcp.go @@ -1068,7 +1068,7 @@ func injectAuthMetadata(ctx context.Context, args map[string]interface{}) map[st if authMeta == nil { return args } - enriched := make(map[string]interface{}, len(args)+len(authMeta)) + enriched := make(map[string]interface{}, len(args)) for k, v := range args { enriched[k] = v }