Repository navigation
Add MCP client integration for external tool servers - #61
Conversation
Signed-off-by: Pavel Anni <[email protected]>
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]>
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughThis 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 ChangesMCP Client Integration
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~55 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
- 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]>
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (12)
CLAUDE.mdgo.modinternal/cmd/agentconfig.gointernal/cmd/serve.gointernal/mcpclient/mcpclient.gointernal/mcpclient/mcpclient_test.gointernal/mcpclient/tool.gointernal/mcpclient/tool_test.gointernal/mcpclient/transport.gointernal/mcpclient/transport_test.gotestdata/mcp-agent/agent-config.yamltestdata/mcp-agent/system-prompt.txt
| type mcpTool struct { | ||
| prefix string | ||
| name string | ||
| desc string | ||
| schema map[string]any | ||
| session *mcp.ClientSession | ||
| } |
There was a problem hiding this comment.
🛠️ 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...) |
There was a problem hiding this comment.
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.
| 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]>
Summary
Closes #2
github.com/modelcontextprotocol/go-sdk(v1.6.0) for protocol handlingagent-config.yamlundertools.mcpsectionDesign
New
internal/mcpclient/package with three files:transport.gotool.gomcpclient.goMCP 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
Test plan
make lintpasses with zero issuesSummary by CodeRabbit
Release Notes
New Features
mcpconfiguration section in agent-config.yaml for server setup