Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(server): attribute MCP traffic in observability (route + identity) (#3494)

Colter Dahlberg78a143eebae2
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 607befe0a..7dd62e12a 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -711,10 +711,23 @@ def create_app(
# MCP endpoint — serves 5 tools (search, read, store, forget, health)
# via streamable HTTP for Claude Code and other MCP clients.
- from starlette.routing import Route
+ from starlette.routing import Match, Route
from openviking.server.mcp_endpoint import create_mcp_app
- app.routes.append(Route("/mcp", endpoint=create_mcp_app(), methods=["GET", "POST", "DELETE"]))
+ class _ScopedRoute(Route):
+ """Expose the selected route through ``scope["route"]``, matching
+ ``APIRoute.matches``, so outer observability can resolve the static
+ ``/mcp`` route template."""
+
+ def matches(self, scope):
+ match, child_scope = super().matches(scope)
+ if match != Match.NONE:
+ child_scope["route"] = self
+ return match, child_scope
+
+ app.routes.append(
+ _ScopedRoute("/mcp", endpoint=create_mcp_app(), methods=["GET", "POST", "DELETE"])
+ )
return app
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index 697bfb058..be3f79ed7 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -54,6 +54,7 @@ from openviking.server.local_input_guard import (
from openviking.server.resource_ingest import ingest_temp_upload
from openviking.server.temp_upload_store import TempUploadStore
from openviking.server.upload_token_store import upload_token_store
+from openviking.telemetry.span_models import update_root_span_identity
from openviking.utils.search_filters import SearchContextTypeInput, merge_search_filter
from openviking_cli.exceptions import (
InvalidArgumentError,
@@ -188,10 +189,24 @@ class _IdentityASGIMiddleware:
)
return await resp(scope, receive, send)
+ # Mirror the identity fallback RequestContext applies below, so the
+ # observability stamp and the request context never disagree.
+ effective_account_id = identity.account_id or "default"
+ effective_user_id = identity.user_id or "default"
+ # Stamp the resolved identity onto the outer request's root
+ # observability context, mirroring what get_request_context does for
+ # REST routes. MCP authentication bypasses FastAPI's REST context
+ # dependency; request.state shares scope["state"] with the outer app,
+ # where the observability middleware attached root_span_attrs.
+ update_root_span_identity(
+ request_state=request.state,
+ account_id=effective_account_id,
+ user_id=effective_user_id,
+ )
ctx = RequestContext(
user=UserIdentifier(
- identity.account_id or "default",
- identity.user_id or "default",
+ effective_account_id,
+ effective_user_id,
),
role=identity.role,
actor_peer_id=actor_peer_id,
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 7a4db5828..988e1b1fa 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -877,3 +877,80 @@ def test_mcp_route_registered(app):
"""Verify the /mcp route exists in the app."""
mcp_routes = [r for r in app.routes if hasattr(r, "path") and r.path == "/mcp"]
assert len(mcp_routes) == 1
+
+
+def test_mcp_route_sets_scope_route(app):
+ """The /mcp route must resolve ``scope["route"]`` on match so the
+ observability middleware's route-template lookup attributes MCP traffic
+ to ``/mcp`` instead of falling back to ``/__unmatched__``."""
+ from starlette.routing import Match
+
+ mcp_route = next(r for r in app.routes if getattr(r, "path", None) == "/mcp")
+
+ scope = {"type": "http", "method": "POST", "path": "/mcp", "headers": []}
+ match, child_scope = mcp_route.matches(scope)
+
+ assert match != Match.NONE
+ assert child_scope["route"] is mcp_route
+
+
+def test_mcp_route_unmatched_paths_keep_falling_back(app):
+ """Non-matching paths must not gain ``scope["route"]`` — the 404 fallback
+ to ``/__unmatched__`` (low-cardinality protection) stays intact."""
+ from starlette.routing import Match
+
+ mcp_route = next(r for r in app.routes if getattr(r, "path", None) == "/mcp")
+
+ scope = {"type": "http", "method": "POST", "path": "/mcp-does-not-exist", "headers": []}
+ match, child_scope = mcp_route.matches(scope)
+
+ assert match == Match.NONE
+ assert "route" not in child_scope
+
+
+async def test_mcp_middleware_stamps_root_span_identity():
+ """Identity resolved from the auth headers must be stamped onto the outer
+ request's root span attributes, so MCP traffic is audited under the real
+ account/user instead of ``__unknown__``."""
+ from openviking.telemetry.span_models import RootSpanAttributes
+
+ root_attrs = RootSpanAttributes(
+ http_method="POST",
+ http_route="/mcp",
+ request_id="req-test",
+ )
+
+ async def downstream(scope, receive, send):
+ response = httpx.Response(200, json={"ok": True})
+ await send(
+ {
+ "type": "http.response.start",
+ "status": response.status_code,
+ "headers": [(b"content-type", b"application/json")],
+ }
+ )
+ await send({"type": "http.response.body", "body": response.content})
+
+ app = FastAPI()
+ app.state.config = SimpleNamespace(get_effective_auth_mode=lambda: AuthMode.DEV)
+ app.state.auth_plugin = DevAuthPlugin()
+ app.routes.append(Route("/mcp", endpoint=_IdentityASGIMiddleware(downstream), methods=["POST"]))
+
+ async def seed_root_span(scope, receive, send):
+ # Mirrors the outer observability middleware attaching root_span_attrs
+ # to scope["state"] before routing.
+ if scope["type"] == "http":
+ scope.setdefault("state", {})["root_span_attrs"] = root_attrs
+ await app(scope, receive, send)
+
+ transport = httpx.ASGITransport(app=seed_root_span)
+ async with httpx.AsyncClient(transport=transport, base_url="http://ov.test") as client:
+ response = await client.post(
+ "/mcp",
+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},
+ headers={"X-OpenViking-Account": "acct-1", "X-OpenViking-User": "user-1"},
+ )
+
+ assert response.status_code == 200
+ assert root_attrs.account_id == "acct-1"
+ assert root_attrs.user_id == "user-1"