Skip to content

Add MCP client integration for external tool servers - #61

Merged
pavelanni merged 10 commits into
mainfrom
feature/mcp-client-integration
May 8, 2026
Merged

pavelanni merged 10 commits into
mainfrom
feature/mcp-client-integration

Conversation

@pavelanni

@pavelanni pavelanni commented May 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes #2

  • Add MCP client capabilities so agents can connect to external MCP tool servers via stdio or streamable HTTP transports
  • MCP tools integrate transparently into the existing tool registry — the agentic loop and LLM providers are unaware of the difference
  • Uses the official github.com/modelcontextprotocol/go-sdk (v1.6.0) for protocol handling
  • Configuration via agent-config.yaml under tools.mcp section

Design

New internal/mcpclient/ package with three files:

File Responsibility
transport.go Config types, validation, transport factory
tool.go MCP-to-Tool adapter, result conversion
mcpclient.go Manager: connect, discover tools, lifecycle

MCP tools are registered via RegisterAlwaysAllowed() — configuring a server implies trust. Tool names are prefixed with server name to prevent collisions (e.g., weather_get_forecast).

Configuration example

tools:
  mcp:
    - name: weather
      transport: streamable_http
      url: "http://weather-tool:8000/mcp"
    - name: localtools
      transport: stdio
      command: python
      args: ["-m", "local_mcp_server"]
      env:
        LOG_LEVEL: debug

Test plan

  • Config validation tests (6 cases: valid/invalid for both transports, missing name, unknown transport)
  • YAML parsing test for MCPServerConfig
  • Tool adapter tests with in-memory MCP servers (name prefixing, text results, multi-block concatenation, error flag mapping)
  • Manager tests (single server, multiple servers, duplicate name rejection, empty config, end-to-end tool execution)
  • All existing tests pass unchanged
  • make lint passes with zero issues

Summary by CodeRabbit

Release Notes

New Features

  • Added support for connecting to Model Context Protocol (MCP) servers to extend available tools
  • Configure multiple MCP servers using HTTP or stdio-based connections
  • Tools from configured MCP servers are automatically discovered and integrated for agent use
  • New mcp configuration section in agent-config.yaml for server setup

pavelanni added 8 commits May 7, 2026 11:38
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Implements Task 2 of MCP client integration. Adds MCPServerConfig type
with validation and transport factory supporting both streamable_http
and stdio transports. Follows TDD with 6 test cases covering:
- Valid streamable_http and stdio configs
- Missing required fields (URL, command, name)
- Unknown transport types

The transport factory creates mcp.StreamableClientTransport for HTTP
and mcp.CommandTransport for stdio, with proper environment variable
handling for subprocess execution.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Implements pkg/tools.Tool wrapper for MCP tools:
- Name prefixing (server_toolname)
- Schema pass-through
- Result conversion (text extraction, error handling)
- Multi-block text concatenation with newlines

Test coverage:
- Name/description metadata
- Single and multi-block text results
- Error result propagation

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
- Manager validates configs, creates transports, connects to servers
- Auto-discovers tools from all servers via ListTools
- Prefixes tool names with server name to avoid conflicts
- Fails fast on duplicate server names or tool name collisions
- Returns all tools as tools.Tool implementations via Tools()
- Includes Close() for graceful shutdown of all connections
- Test coverage: single/multiple servers, empty config, duplicates, execution

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Add MCP configuration to agent-config.yaml schema and connect
MCP servers during serve startup when configured. MCP tools are
registered as always-allowed and available in phase 2 agentic mode.

Changes:
- Add mcpclient.MCPServerConfig field to ToolsConfig
- Initialize MCP manager in serve.go when mcp config present
- Register MCP tools as always-allowed in tool registry

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
- Add testdata/mcp-agent/ with example agent-config.yaml using MCP
- Add YAML parsing test for MCPServerConfig
- Add internal/mcpclient/ to CLAUDE.md project structure table

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@pavelanni has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 51 minutes and 49 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 955d5127-8bc7-4350-943d-79affb65a97d

📥 Commits

Reviewing files that changed from the base of the PR and between cb02ff5 and fef4d8a.

📒 Files selected for processing (1)
  • internal/mcpclient/mcpclient.go
📝 Walkthrough

Walkthrough

This PR adds Model Context Protocol (MCP) client integration to DocsClaw, enabling agents to connect to external MCP tool servers via HTTP/SSE or stdio transports. The implementation includes transport configuration, server connection management, tool discovery, and integration with the existing tool registry through a new internal/mcpclient package.

Changes

MCP Client Integration

Layer / File(s) Summary
Transport Configuration
internal/mcpclient/transport.go, internal/mcpclient/transport_test.go
MCPServerConfig struct defines server name, transport type (streamable_http or stdio), URL/command/args/env, with validation enforcing transport-specific field requirements and newTransport() creating the appropriate mcp.Transport instance.
MCP Manager & Tool Discovery
internal/mcpclient/mcpclient.go, internal/mcpclient/mcpclient_test.go
Manager connects to multiple configured MCP servers, lists their tools, prefixes tool names per server to avoid collisions, and exposes them via Tools() as tools.Tool instances. Connection/discovery happens in NewManager with fast-fail on errors or duplicates; Close() disconnects all sessions.
Tool Adapter
internal/mcpclient/tool.go, internal/mcpclient/tool_test.go
mcpTool adapts MCP tools to the project's tools interface, implementing Name(), Description(), Parameters(), and Execute(). The Execute() method calls mcp.ClientSession.CallTool and convertResult() extracts/joins text content, logs warnings for non-text content, and maps MCP error state to tools.Errorf or tools.OK.
Agent Integration
internal/cmd/agentconfig.go, internal/cmd/serve.go, go.mod
ToolsConfig struct adds MCP []mcpclient.MCPServerConfig field (YAML key mcp). In serve.go phase 2, when MCP configs exist, an Manager is created, connected, and each tool registered via RegisterAlwaysAllowed. Dependency github.com/modelcontextprotocol/go-sdk v1.6.0 is added.
Configuration & Documentation
CLAUDE.md, testdata/mcp-agent/agent-config.yaml, testdata/mcp-agent/system-prompt.txt
Project structure documentation updated. Example agent config defines two MCP servers (weather via HTTP, localtools via stdio) and example system prompt for test agent.

Sequence Diagram

sequenceDiagram
    participant Agent as Agent Loop
    participant Mgr as MCP Manager
    participant Srv as MCP Server
    participant TR as Tool Registry

    Agent->>Agent: Load agent config
    Agent->>Mgr: NewManager(mcp_configs)
    Mgr->>Srv: Connect via transport
    Mgr->>Srv: ListTools()
    Srv-->>Mgr: Tool definitions
    Mgr->>Mgr: Build mcpTool wrappers<br/>(prefix + name)
    Mgr->>TR: RegisterAlwaysAllowed(tools)
    
    loop Tool Execution
        Agent->>TR: Find tool by name
        TR-->>Agent: mcpTool
        Agent->>Agent: mcpTool.Execute(args)
        Agent->>Srv: CallTool(name, arguments)
        Srv-->>Agent: TextContent + IsError
        Agent->>Agent: Convert to ToolResult
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~55 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.17% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Add MCP client integration for external tool servers' is clear, specific, and directly describes the main change: adding MCP client capabilities to the codebase.
Linked Issues check ✅ Passed Code changes fully implement all primary objectives from issue #2: MCP client integration with stdio/streamable HTTP transport support, agent-config.yaml configuration, tool registry integration, and comprehensive testing.
Out of Scope Changes check ✅ Passed All changes are scoped to MCP client integration: internal/mcpclient implementation, agent config updates, serve.go wiring, documentation, and test fixtures. No unrelated modifications.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/mcp-client-integration

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

Comment @coderabbitai help to get the list of available commands and usage tips.

- Consistent error message format in validate() (no name available)
- Clarify MCP client implementation version comment

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni marked this pull request as ready for review May 8, 2026 01:51

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/mcpclient/mcpclient.go`:
- Around line 70-74: The newly created session (variable session / conn) can
leak if an error occurs before it's appended to mgr (e.g., after calling
session.ListTools or when detecting duplicate tools); fix by appending the conn
to mgr immediately after a successful dial/create of session or, if you prefer
keeping append later, ensure you call session.Close() (or equivalent) on every
early-return/error path (ListTools error, duplicate-tool error in the loop, and
other failure branches). Update the error paths around session.ListTools, the
duplicate-tool handling loop, and the later return branches to explicitly close
session (or move the append-to-mgr action to right after connect) so no active
sessions are left unclosed; keep using mgr.Close() for manager cleanup as
before.

In `@internal/mcpclient/tool.go`:
- Around line 12-18: The package lacks an exported constructor for the mcpTool
implementation; add a function like NewMCPTool (exported) that accepts the
required inputs (prefix, name, desc, schema, session or a config struct) and
returns the tools.Tool interface by instantiating &mcpTool{...}; update callers
(e.g., the manager) to use NewMCPTool instead of constructing mcpTool directly
so the package follows the tools.Tool construction contract and mcpTool remains
unexported.

In `@internal/mcpclient/transport.go`:
- Line 46: The linter flags the use of exec.Command in the CommandTransport
code; update the exec.Command invocation (the line creating cmd in
CommandTransport) to add a targeted nolint suppression with a short
justification comment explaining why exec.Command is intentionally used (process
lifecycle is owned by mcp.CommandTransport and matches SDK pattern) so make lint
no longer fails; keep the nolint scoped to the noctx check (//nolint:noctx) and
include the justification on the same or preceding line.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Enterprise

Run ID: 07b5fe00-c94d-45ae-87d2-576bcd50632c

📥 Commits

Reviewing files that changed from the base of the PR and between e33adbe and cb02ff5.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (12)
  • CLAUDE.md
  • go.mod
  • internal/cmd/agentconfig.go
  • internal/cmd/serve.go
  • internal/mcpclient/mcpclient.go
  • internal/mcpclient/mcpclient_test.go
  • internal/mcpclient/tool.go
  • internal/mcpclient/tool_test.go
  • internal/mcpclient/transport.go
  • internal/mcpclient/transport_test.go
  • testdata/mcp-agent/agent-config.yaml
  • testdata/mcp-agent/system-prompt.txt

Comment thread internal/mcpclient/mcpclient.go Resolved
Comment on lines +12 to +18
type mcpTool struct {
prefix string
name string
desc string
schema map[string]any
session *mcp.ClientSession
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add an exported constructor returning tools.Tool

This tool implementation currently has no exported constructor. Please add one (and prefer using it from the manager) so the package follows the project’s tool-construction contract.

Proposed fix
 type mcpTool struct {
 	prefix  string
 	name    string
 	desc    string
 	schema  map[string]any
 	session *mcp.ClientSession
 }
+
+func NewTool(prefix, name, desc string, schema map[string]any, session *mcp.ClientSession) tools.Tool {
+	if schema == nil {
+		schema = map[string]any{"type": "object"}
+	}
+	return &mcpTool{
+		prefix:  prefix,
+		name:    name,
+		desc:    desc,
+		schema:  schema,
+		session: session,
+	}
+}

As per coding guidelines: internal/*/tool.go: Tool implementations must export a constructor that returns tools.Tool interface.

Also applies to: 20-33

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/mcpclient/tool.go` around lines 12 - 18, The package lacks an
exported constructor for the mcpTool implementation; add a function like
NewMCPTool (exported) that accepts the required inputs (prefix, name, desc,
schema, session or a config struct) and returns the tools.Tool interface by
instantiating &mcpTool{...}; update callers (e.g., the manager) to use
NewMCPTool instead of constructing mcpTool directly so the package follows the
tools.Tool construction contract and mcpTool remains unexported.

Endpoint: c.URL,
}
case "stdio":
cmd := exec.Command(c.Command, c.Args...)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

exec.Command triggers noctx lint error — make lint will fail

The noctx linter requires exec.CommandContext whenever a context is available in scope (or accessible). This is flagged at error level (not warning), so make lint will exit non-zero.

Since mcp.CommandTransport owns the process lifecycle independently (the official SDK docs show exec.Command used directly in the same pattern), the cleanest fix is a targeted //nolint suppression with a justification comment rather than an API signature change:

🛠️ Proposed fix
-		cmd := exec.Command(c.Command, c.Args...)
+		// mcp.CommandTransport manages the process lifecycle (Start/Stop).
+		// A context-bound command is not needed here; the transport handles teardown.
+		cmd := exec.Command(c.Command, c.Args...) //nolint:noctx
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cmd := exec.Command(c.Command, c.Args...)
// mcp.CommandTransport manages the process lifecycle (Start/Stop).
// A context-bound command is not needed here; the transport handles teardown.
cmd := exec.Command(c.Command, c.Args...) //nolint:noctx
🧰 Tools
🪛 golangci-lint (2.12.1)

[error] 46-46: os/exec.Command must not be called. use os/exec.CommandContext

(noctx)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/mcpclient/transport.go` at line 46, The linter flags the use of
exec.Command in the CommandTransport code; update the exec.Command invocation
(the line creating cmd in CommandTransport) to add a targeted nolint suppression
with a short justification comment explaining why exec.Command is intentionally
used (process lifecycle is owned by mcp.CommandTransport and matches SDK
pattern) so make lint no longer fails; keep the nolint scoped to the noctx check
(//nolint:noctx) and include the justification on the same or preceding line.

Move conn append to mgr.servers immediately after successful Connect
so mgr.Close() includes the session in cleanup on any subsequent error.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Pavel Anni <[email protected]>
@pavelanni
pavelanni merged commit b133bfc into main May 8, 2026
3 checks passed
@pavelanni
pavelanni deleted the feature/mcp-client-integration branch May 8, 2026 02:00
@pavelanni pavelanni mentioned this pull request May 8, 2026
2 tasks done
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.

MCP client integration for external tool servers

1 participant