"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(mcp): isolate goal sessions per MCP connection, not per process
Lanre Shittu643123c814d9
diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex 727723100..5dce740ec 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -349,19 +349,29 @@ def _get_goal_store():_mcp_session_id: str | None = None-def _resolve_session_id(session_id: str = "") -> str:- """Resolve the goal session, defaulting to this server process's session.+def _resolve_session_id(session_id: str = "", ctx: Context | None = None) -> str:+ """Resolve the goal session: explicit id, then per-connection id, then+ one id per server process.The in-process tool registry injects the host session and keeps``session_id`` out of its required schema. MCP has no such injection point,so these tools used to mark the id required — asking the model to invent aninternal identifier it has no way to know, the opposite contract from the- local path (#885). Default instead to one stable id per server process,- which is the closest MCP equivalent of a host-owned session, while still- honouring an explicit id from a client that tracks its own conversations.+ local path (#885). Default instead to a session id, while still honouring+ an explicit id from a client that tracks its own conversations.++ A single server process can serve many concurrent MCP connections (the+ http/sse transports this file documents), so the process-wide fallback on+ its own would collapse every such caller onto one goal session. ``ctx``,+ when available, carries FastMCP's own per-connection session id (the real+ ``mcp-session-id`` header for StreamableHTTP, a cached id for the other+ transports) and takes precedence over the process fallback for exactly+ that reason.Args:session_id: Optional client-supplied session id.+ ctx: Optional MCP request context; supplies a per-connection id when+ the tool is invoked through a live MCP request.Returns:A non-empty session id.@@ -369,6 +379,11 @@ def _resolve_session_id(session_id: str = "") -> str:global _mcp_session_idif cleaned := session_id.strip():return cleaned+ if ctx is not None:+ try:+ return ctx.session_id+ except RuntimeError:+ passif _mcp_session_id is None:import uuid@@ -540,6 +555,7 @@ def start_research_goal(token_budget: int | None = None,turn_budget: int | None = None,time_budget_seconds: int | None = None,+ ctx: Context | None = None,) -> str:"""Create or replace the current finance research goal for a session.@@ -562,7 +578,7 @@ def start_research_goal(try:clean_criteria = _clean_list(criteria) or _default_goal_criteria()goal = _get_goal_store().replace_goal(- session_id=_resolve_session_id(session_id),+ session_id=_resolve_session_id(session_id, ctx),objective=objective,criteria=clean_criteria,ui_summary=ui_summary,@@ -580,7 +596,7 @@ def start_research_goal(@mcp.tool-def get_research_goal(session_id: str = "") -> str:+def get_research_goal(session_id: str = "", ctx: Context | None = None) -> str:"""Return the current finance research goal snapshot for a session.Args:@@ -588,7 +604,7 @@ def get_research_goal(session_id: str = "") -> str:its own sessions; this server then uses one id per process."""try:- snapshot = _get_goal_store().get_current_snapshot(_resolve_session_id(session_id))+ snapshot = _get_goal_store().get_current_snapshot(_resolve_session_id(session_id, ctx))except ValueError as exc:return _json_error(str(exc), error_type="validation")if snapshot is None:@@ -621,6 +637,7 @@ def add_goal_evidence(confidence: str | None = None,caveat: str | None = None,contradicts_claim_ids: _lenient_str_list_opt = None,+ ctx: Context | None = None,) -> str:"""Append traceable evidence to a finance research goal.@@ -654,7 +671,7 @@ def add_goal_evidence(from src.goal import EvidenceInput, StaleGoalErrorevidence = _get_goal_store().append_evidence(- session_id=_resolve_session_id(session_id),+ session_id=_resolve_session_id(session_id, ctx),goal_id=goal_id.strip(),expected_goal_id=expected_goal_id.strip(),evidence=EvidenceInput(@@ -700,6 +717,7 @@ def update_research_goal_status(session_id: str = "",audit: _lenient_dict_list_opt = None,recap: str | None = None,+ ctx: Context | None = None,) -> str:"""Update a finance research goal status after an audit.@@ -720,7 +738,7 @@ def update_research_goal_status(from src.goal import GoalStatus, StaleGoalErrorupdated = _get_goal_store().update_status(- session_id=_resolve_session_id(session_id),+ session_id=_resolve_session_id(session_id, ctx),goal_id=goal_id.strip(),expected_goal_id=expected_goal_id.strip(),status=GoalStatus(status),diff --git a/agent/tests/test_mcp_goal_session_isolation.py b/agent/tests/test_mcp_goal_session_isolation.pynew file mode 100644index 000000000..5d6854838--- /dev/null+++ b/agent/tests/test_mcp_goal_session_isolation.py@@ -0,0 +1,50 @@+"""Regression: two concurrent MCP connections must not share a goal session.++Pre-fix: _resolve_session_id() fell back to a single process-wide id+(_mcp_session_id) whenever a caller omitted session_id, which is correct+for stdio (one process per client) but wrong for the http/sse transports+this file documents, where one process serves many concurrent+connections. Every such caller collapsed onto the same goal session, so+one client's start_research_goal() silently superseded another's.++Post-fix: _resolve_session_id() prefers FastMCP's own per-connection+ctx.session_id (real mcp-session-id header for StreamableHTTP, a cached+id for the other transports) before falling back to the process-wide id,+so concurrent connections that both omit session_id still get isolated+goal sessions.+"""++from __future__ import annotations++import asyncio+import json++from fastmcp import Client++import mcp_server as ms+++def test_two_concurrent_clients_do_not_share_a_goal_session(tmp_path, monkeypatch):+ from src.goal import GoalStore++ monkeypatch.setattr(ms, "_goal_store", GoalStore(db_path=tmp_path / "g.db"))+ monkeypatch.setattr(ms, "_mcp_session_id", None)++ async def scenario():+ async with Client(ms.mcp) as client_a, Client(ms.mcp) as client_b:+ await client_a.call_tool("start_research_goal", {"objective": "USER A thesis: NVDA momentum"})+ await client_b.call_tool("start_research_goal", {"objective": "USER B thesis: bond duration hedge"})+ ra = await client_a.call_tool("get_research_goal", {})+ rb = await client_b.call_tool("get_research_goal", {})+ return json.loads(ra.content[0].text), json.loads(rb.content[0].text)++ snap_a, snap_b = asyncio.run(scenario())+ objective_a = snap_a["snapshot"]["goal"]["objective"]+ objective_b = snap_b["snapshot"]["goal"]["objective"]++ assert objective_a == "USER A thesis: NVDA momentum", (+ f"client A's own get_research_goal() returned {objective_a!r} instead of "+ "its own objective — the two connections shared one goal session"+ )+ assert objective_b == "USER B thesis: bond duration hedge"+ assert snap_a["snapshot"]["goal"]["session_id"] != snap_b["snapshot"]["goal"]["session_id"]