Skip to content

Conversation

rholinshead
Copy link
Member

@rholinshead rholinshead commented Aug 25, 2025

Description

Currently, workflow tools are attempted to be re-registered during each sse request to an app-associated mcp server:

INFO:mcp_agent:[mcp_agent.server.app_server] Workflow BasicAgentWorkflow started with workflow ID BasicAgentWorkflow-05052bde-b3a5-4e4c-8995-90e4d03d9912 and run ID 0198e1c1-edc0-7a64-9572-1ec2d3a43d3c. Parameters: {'input': 'Print the first 2 paragraphs of https://modelcontextprotocol.io/introduction'}
INFO:     127.0.0.1:59463 - "POST /messages/?session_id=9e7c609706a24436884f58ee5ad43c8a HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type ListToolsRequest
INFO:     127.0.0.1:59463 - "POST /messages/?session_id=9e7c609706a24436884f58ee5ad43c8a HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
INFO:     127.0.0.1:59484 - "POST /messages/?session_id=9e7c609706a24436884f58ee5ad43c8a HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
WARNING:mcp.server.fastmcp.tools.tool_manager:Tool already exists: workflows-BasicAgentWorkflow-run
WARNING:mcp.server.fastmcp.tools.tool_manager:Tool already exists: workflows-BasicAgentWorkflow-get_status
WARNING:mcp.server.fastmcp.tools.tool_manager:Tool already exists: workflows-PauseResumeWorkflow-run
WARNING:mcp.server.fastmcp.tools.tool_manager:Tool already exists: workflows-PauseResumeWorkflow-get_status
INFO:     127.0.0.1:59503 - "GET /sse HTTP/1.1" 200 OK

The reasoning is because fastmcp has a handle_sse callback for sse requests which calls server.run() (see here) and enters lifespan context per each request. And entering that context calls create_workflow_tools again before yielding server_context, i.e. per-request/per-session app initialization/tools registration.

Our app initialization is already idempotent, so this PR updates the workflow tools registration to be similarly idempotent per mcp instance.

Testing

make tests

Run the mcp-agent/examples/mcp_agent_server/temporal example and spawn two clients. Without this fix, see the above warnings about tools already existing. With this fix, no warnings and the client results are still correct.

INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:mcp_agent:[mcp_agent.core.context] Configuring logger with level: debug
INFO:mcp_agent:[mcp_agent.basic_agent_server] Loading subagents from configuration...
INFO:mcp_agent:[mcp_agent.basic_agent_server] MCPApp initialized
INFO:     127.0.0.1:50176 - "GET /sse HTTP/1.1" 200 OK
INFO:     127.0.0.1:50177 - "POST /messages/?session_id=68c78373fdb94fa79af24cfcbb69d034 HTTP/1.1" 202 Accepted
INFO:     127.0.0.1:50177 - "POST /messages/?session_id=68c78373fdb94fa79af24cfcbb69d034 HTTP/1.1" 202 Accepted
INFO:     127.0.0.1:50177 - "POST /messages/?session_id=68c78373fdb94fa79af24cfcbb69d034 HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
[DEBUG] 2025-08-25T13:15:41 
workflow.BasicAgentWorkflow - Initializing 
workflow BasicAgentWorkflow
[DEBUG] 2025-08-25T13:15:41 
mcp_agent.executor.temporal.workflow_signal - 
Attaching signal handler to workflow 
BasicAgentWorkflow
[DEBUG] 2025-08-25T13:15:41 
workflow.BasicAgentWorkflow - Workflow started 
with workflow ID: 
BasicAgentWorkflow-cdbcb8b0-b715-418e-9112-613ff
6cd97e8, run ID: 
0198e23a-81d3-7242-af0f-22258d3f2a3d
[INFO] 2025-08-25T13:15:41 
mcp_agent.server.app_server - Workflow 
BasicAgentWorkflow started with workflow ID 
BasicAgentWorkflow-cdbcb8b0-b715-418e-9112-613ff
6cd97e8 and run ID 
0198e23a-81d3-7242-af0f-22258d3f2a3d. 
Parameters: {'input': 'Print the first 2 
paragraphs of 
https://modelcontextprotocol.io/introduction'}
INFO:mcp_agent:[mcp_agent.server.app_server] Workflow BasicAgentWorkflow started with workflow ID BasicAgentWorkflow-cdbcb8b0-b715-418e-9112-613ff6cd97e8 and run ID 0198e23a-81d3-7242-af0f-22258d3f2a3d. Parameters: {'input': 'Print the first 2 paragraphs of https://modelcontextprotocol.io/introduction'}
INFO:     127.0.0.1:50177 - "POST /messages/?session_id=68c78373fdb94fa79af24cfcbb69d034 HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type ListToolsRequest
INFO:     127.0.0.1:50177 - "POST /messages/?session_id=68c78373fdb94fa79af24cfcbb69d034 HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
INFO:     127.0.0.1:50192 - "POST /messages/?session_id=68c78373fdb94fa79af24cfcbb69d034 HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
INFO:     127.0.0.1:50196 - "GET /sse HTTP/1.1" 200 OK
INFO:     127.0.0.1:50197 - "POST /messages/?session_id=f3b522b7d4234a5b803d59a2ee09715e HTTP/1.1" 202 Accepted
INFO:     127.0.0.1:50197 - "POST /messages/?session_id=f3b522b7d4234a5b803d59a2ee09715e HTTP/1.1" 202 Accepted
INFO:     127.0.0.1:50197 - "POST /messages/?session_id=f3b522b7d4234a5b803d59a2ee09715e HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
[DEBUG] 2025-08-25T13:15:51 
workflow.BasicAgentWorkflow - Initializing 
workflow BasicAgentWorkflow
[DEBUG] 2025-08-25T13:15:51 
mcp_agent.executor.temporal.workflow_signal - 
Attaching signal handler to workflow 
BasicAgentWorkflow
[DEBUG] 2025-08-25T13:15:51 
workflow.BasicAgentWorkflow - Workflow started 
with workflow ID: 
BasicAgentWorkflow-952def02-133f-4e5c-8d00-b6f44
7bfdd8d, run ID: 
0198e23a-a740-73ef-ac83-582ae66d1543
[INFO] 2025-08-25T13:15:51 
mcp_agent.server.app_server - Workflow 
BasicAgentWorkflow started with workflow ID 
BasicAgentWorkflow-952def02-133f-4e5c-8d00-b6f44
7bfdd8d and run ID 
0198e23a-a740-73ef-ac83-582ae66d1543. 
Parameters: {'input': 'Print the first 2 
paragraphs of 
https://modelcontextprotocol.io/introduction'}
INFO:mcp_agent:[mcp_agent.server.app_server] Workflow BasicAgentWorkflow started with workflow ID BasicAgentWorkflow-952def02-133f-4e5c-8d00-b6f447bfdd8d and run ID 0198e23a-a740-73ef-ac83-582ae66d1543. Parameters: {'input': 'Print the first 2 paragraphs of https://modelcontextprotocol.io/introduction'}
INFO:     127.0.0.1:50197 - "POST /messages/?session_id=f3b522b7d4234a5b803d59a2ee09715e HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type ListToolsRequest
INFO:     127.0.0.1:50197 - "POST /messages/?session_id=f3b522b7d4234a5b803d59a2ee09715e HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
INFO:     127.0.0.1:50201 - "POST /messages/?session_id=68c78373fdb94fa79af24cfcbb69d034 HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
[DEBUG] 2025-08-25T13:15:52 
workflow.BasicAgentWorkflow - Cleaning up 
workflow BasicAgentWorkflow
INFO:     127.0.0.1:50207 - "POST /messages/?session_id=f3b522b7d4234a5b803d59a2ee09715e HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
INFO:     127.0.0.1:50208 - "POST /messages/?session_id=68c78373fdb94fa79af24cfcbb69d034 HTTP/1.1" 202 Accepted
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
[DEBUG] 2025-08-25T13:15:59 
workflow.BasicAgentWorkflow - Cleaning up 

Summary by CodeRabbit

  • Bug Fixes
    • Prevents duplicate workflow tools after reconnections, making registration idempotent and tool lists consistent.
  • Performance
    • Reduces overhead during repeated initializations, improving responsiveness on reconnect.
  • Reliability
    • Ensures workflow tool registrations persist across reconnections for stable behavior.
  • Public API
    • Exposes additional server components for advanced integrations.
  • Tests
    • Adds comprehensive coverage for workflow tool lifecycle, idempotent registration, and reconnection scenarios.

Copy link

coderabbitai bot commented Aug 25, 2025

Walkthrough

Introduces a per-FastMCP registry to track registered workflow tools, updates ServerContext and create_workflow_tools to check and persist this registry, and adds tests validating idempotent tool registration and persistence across recreated ServerContext instances (e.g., SSE lifecycles). Exposes ServerContext and create_workflow_tools for testing.

Changes

Cohort / File(s) Summary
Server runtime: per-workflow tool registry and idempotency
src/mcp_agent/server/app_server.py
Adds _get_registered_workflow_tools(mcp) -> Set[str]; augments ServerContext to keep _registered_workflow_tools on FastMCP; updates ServerContext.register_workflow and create_workflow_tools to consult/update the registry and avoid duplicate per-workflow tool creations; minor typing updates.
Tests: lifecycle and idempotency of workflow tools
tests/server/test_app_server.py
Exposes ServerContext and create_workflow_tools for tests; adds tests verifying initial registration for multiple workflows, persistence across new ServerContext instances, dynamic additions, and idempotent re-invocations without duplicate tool creation.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant ServerContext
  participant create_workflow_tools
  participant FastMCP as FastMCP (registry)
  participant ToolReg as Tool Registration

  Client->>ServerContext: initialize (SSE lifecycle may recreate)
  Note over ServerContext,FastMCP: ServerContext binds to existing FastMCP

  Client->>create_workflow_tools: invoke with (mcp, server_context)
  create_workflow_tools->>FastMCP: read _registered_workflow_tools
  alt workflow not yet registered
    create_workflow_tools->>ToolReg: register run/get_status tools for workflow
    create_workflow_tools->>FastMCP: update _registered_workflow_tools
  else already registered
    Note over create_workflow_tools: Skip creating duplicate tools
  end

  Client->>ServerContext: register_workflow(name)
  ServerContext->>FastMCP: check _registered_workflow_tools
  alt not registered
    ServerContext->>ToolReg: create per-workflow tools
    ServerContext->>FastMCP: mark as registered
  else already registered
    Note over ServerContext: No-op
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • petersonbill64

Poem

I hopped through SSE winds anew,
Tools in tow, but none askew—
A registry bur bur burrowed tight,
Guards each workflow, left and right.
No duplicates in moonlit logs,
Just tidy tracks of careful cogs.
Thump! Idempotence—job done right. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/workflow-tools-single-registration

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (6)
src/mcp_agent/server/app_server.py (3)

40-45: Defensive init for _registered_workflow_tools to ensure correct type

Good call persisting the registry on the FastMCP instance. Make it resilient if something pre-attaches a non-set (e.g., list via config/mocking). Normalize to a set once.

Apply this diff:

-        if not hasattr(self.mcp, "_registered_workflow_tools"):
-            setattr(self.mcp, "_registered_workflow_tools", set())
+        tools = getattr(self.mcp, "_registered_workflow_tools", None)
+        if not isinstance(tools, set):
+            tools = set(tools) if tools else set()
+            setattr(self.mcp, "_registered_workflow_tools", tools)

71-76: register_workflow skips tool creation when workflow already exists

As written, tool creation only happens when the workflow is newly added to the mapping. If the workflow is already present (e.g., preloaded at app init) but tools weren’t registered (fresh MCP instance, prior cleanup, or external interference), calling register_workflow won’t (re)create the tools.

Move the tool-registration block outside the workflow-addition if to guarantee "ensure tools exist" semantics.

Apply this diff:

-            # Create tools for this workflow if not already registered
-            registered_workflow_tools = _get_registered_workflow_tools(self.mcp)
-            if workflow_name not in registered_workflow_tools:
-                create_workflow_specific_tools(self.mcp, workflow_name, workflow_cls)
-                registered_workflow_tools.add(workflow_name)
+        # Create tools for this workflow if not already registered
+        registered_workflow_tools = _get_registered_workflow_tools(self.mcp)
+        if workflow_name not in registered_workflow_tools:
+            create_workflow_specific_tools(self.mcp, workflow_name, workflow_cls)
+            registered_workflow_tools.add(workflow_name)

Follow-up: If you keep the stricter "only when adding" behavior intentionally, consider documenting it in the method docstring to avoid future confusion.


98-101: Make _get_registered_workflow_tools idempotent and type-safe

This helper should also ensure the attribute exists and is of the expected type. Today it returns a new ephemeral set when missing; most call sites are fine, but making it self-healing tightens guarantees.

Apply this diff:

-def _get_registered_workflow_tools(mcp: FastMCP) -> Set[str]:
-    """Return the set of registered workflow tools for the FastMCP server, if any."""
-    return getattr(mcp, "_registered_workflow_tools", set())
+def _get_registered_workflow_tools(mcp: FastMCP) -> Set[str]:
+    """Return (and ensure) the set of registered workflow tools on the FastMCP server."""
+    tools = getattr(mcp, "_registered_workflow_tools", None)
+    if not isinstance(tools, set):
+        tools = set(tools) if tools else set()
+        setattr(mcp, "_registered_workflow_tools", tools)
+    return tools
tests/server/test_app_server.py (3)

295-303: Decorator tracker is neat; consider reusing via a fixture

The inline decorator tracker is duplicated later in this file. Extracting a small pytest fixture for it will keep tests DRY and easier to tweak if the tool signature changes.

Happy to draft a tiny fixture if you want.


261-358: Great coverage of idempotent registration; add a “pre-existing workflow, missing tools” case

This verifies the common path. One edge case: if server_context.workflows already contains the workflow (preloaded), but _registered_workflow_tools is empty (e.g., new MCP instance), calling register_workflow should still (re)create tools. That’s currently skipped by the surrounding membership check in register_workflow.

You can augment the test suite with a scenario like:

def test_register_workflow_creates_tools_when_workflow_already_present():
    mock_mcp = MagicMock()
    # Intentionally provide an empty/missing registry
    if hasattr(mock_mcp, "_registered_workflow_tools"):
        delattr(mock_mcp, "_registered_workflow_tools")

    tools_created = []
    def track_tool_calls(*args, **kwargs):
        def decorator(func):
            tools_created.append(kwargs.get("name", args[0] if args else "unknown"))
            return func
        return decorator
    mock_mcp.tool = track_tool_calls

    mock_workflow_class = MagicMock()
    mock_workflow_class.__doc__ = "Test workflow"
    mock_run = MagicMock(); mock_run.__name__ = "run"
    mock_workflow_class.run = mock_run

    mock_app = MagicMock()
    mock_context = MagicMock(app=mock_app)
    mock_context.workflow_registry = None
    mock_context.config = MagicMock()
    mock_context.config.execution_engine = "asyncio"
    # Pre-populate workflows mapping
    mock_app.workflows = {"workflow1": mock_workflow_class}

    server_context = ServerContext(mcp=mock_mcp, context=mock_context)

    # Now ensure tools get created even though workflow already exists
    server_context.register_workflow("workflow1", mock_workflow_class)

    assert set(tools_created) == {
        "workflows-workflow1-run",
        "workflows-workflow1-get_status",
    }

If you accept the earlier refactor to register_workflow, this test should pass.


360-433: Persistence across SSE-like lifecycles validated well

This mirrors the FastMCP behavior and confirms the registry lives on the MCP instance, not the ephemeral ServerContext. Nicely done.

Two small extensions (optional):

  • Add a second SSE-cycle that introduces a new workflow (e.g., workflow2) and assert only its tools are created (no duplication for workflow1).
  • Assert isinstance(mock_mcp._registered_workflow_tools, set) is maintained even if someone mutates it (type normalization from earlier refactor will help).
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 64b93d2 and 6d00b54.

📒 Files selected for processing (2)
  • src/mcp_agent/server/app_server.py (5 hunks)
  • tests/server/test_app_server.py (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/mcp_agent/server/app_server.py (2)
src/mcp_agent/core/context.py (1)
  • mcp (98-99)
src/mcp_agent/app.py (1)
  • workflows (166-167)
tests/server/test_app_server.py (1)
src/mcp_agent/server/app_server.py (6)
  • ServerContext (32-90)
  • create_workflow_tools (394-410)
  • app (78-80)
  • workflows (83-85)
  • workflow_registry (88-90)
  • register_workflow (67-75)
🔇 Additional comments (2)
src/mcp_agent/server/app_server.py (1)

403-411: Idempotent per-workflow tool creation looks solid

The registry check + single final setattr ensures consistent state on the FastMCP instance and avoids duplicates across SSE lifecycles. Nicely aligns with the PR objective.

tests/server/test_app_server.py (1)

4-8: Public API imports validated

Importing ServerContext and create_workflow_tools directly from app_server enforces the new API surface. Good to see tests exercising these entry points.

Copy link
Collaborator

@saqadri saqadri left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very elegant fix!

@rholinshead rholinshead merged commit 11a2b9a into main Aug 26, 2025
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants