coder-agent 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coder_agent-0.1.0.dist-info/METADATA +262 -0
- coder_agent-0.1.0.dist-info/RECORD +163 -0
- coder_agent-0.1.0.dist-info/WHEEL +5 -0
- coder_agent-0.1.0.dist-info/entry_points.txt +2 -0
- coder_agent-0.1.0.dist-info/licenses/LICENSE.md +21 -0
- coder_agent-0.1.0.dist-info/top_level.txt +1 -0
- coderagent/__init__.py +20 -0
- coderagent/compat/__init__.py +27 -0
- coderagent/compat/cache_control.py +69 -0
- coderagent/compat/config_spec.py +60 -0
- coderagent/compat/exceptions.py +20 -0
- coderagent/compat/retry.py +27 -0
- coderagent/compat/serialize.py +31 -0
- coderagent/config/__init__.py +1 -0
- coderagent/config/defaults.yaml +103 -0
- coderagent/config/loader.py +264 -0
- coderagent/config/schema.py +548 -0
- coderagent/config/writer.py +218 -0
- coderagent/core/__init__.py +1 -0
- coderagent/core/budget.py +47 -0
- coderagent/core/capabilities.py +136 -0
- coderagent/core/checkpoint.py +164 -0
- coderagent/core/content.py +156 -0
- coderagent/core/context.py +618 -0
- coderagent/core/events.py +83 -0
- coderagent/core/history.py +56 -0
- coderagent/core/instructions.py +99 -0
- coderagent/core/loop.py +702 -0
- coderagent/core/memory.py +56 -0
- coderagent/core/mentions.py +81 -0
- coderagent/core/os_sandbox.py +191 -0
- coderagent/core/otel.py +214 -0
- coderagent/core/protocols.py +38 -0
- coderagent/core/redact.py +49 -0
- coderagent/core/sandbox.py +82 -0
- coderagent/core/schema.py +107 -0
- coderagent/core/session.py +344 -0
- coderagent/core/shell_env.py +74 -0
- coderagent/core/subagent.py +474 -0
- coderagent/core/summarize.py +312 -0
- coderagent/core/telemetry.py +209 -0
- coderagent/core/tokens.py +132 -0
- coderagent/core/trust.py +301 -0
- coderagent/environments/__init__.py +11 -0
- coderagent/environments/bubblewrap.py +150 -0
- coderagent/environments/contree.py +146 -0
- coderagent/environments/docker.py +160 -0
- coderagent/environments/local.py +110 -0
- coderagent/environments/singularity.py +138 -0
- coderagent/environments/swerex_docker.py +79 -0
- coderagent/environments/swerex_modal.py +123 -0
- coderagent/eval/__init__.py +1 -0
- coderagent/eval/compare.py +190 -0
- coderagent/eval/report.py +141 -0
- coderagent/eval/runner.py +368 -0
- coderagent/eval/task.py +194 -0
- coderagent/extensions/__init__.py +1 -0
- coderagent/extensions/hooks.py +121 -0
- coderagent/extensions/plugins.py +217 -0
- coderagent/extensions/reflect.py +342 -0
- coderagent/models/__init__.py +33 -0
- coderagent/models/backends.py +218 -0
- coderagent/models/call.py +18 -0
- coderagent/models/check.py +139 -0
- coderagent/models/gateway.py +60 -0
- coderagent/models/litellm_config.py +70 -0
- coderagent/models/provider.py +98 -0
- coderagent/models/reasoning.py +28 -0
- coderagent/models/router.py +136 -0
- coderagent/models/settings.py +172 -0
- coderagent/models/streaming.py +122 -0
- coderagent/models/verbosity.py +14 -0
- coderagent/paths.py +31 -0
- coderagent/run.py +454 -0
- coderagent/skills/__init__.py +119 -0
- coderagent/skills/errors.py +11 -0
- coderagent/skills/install.py +340 -0
- coderagent/skills/presets/code-review/SKILL.md +35 -0
- coderagent/skills/presets/codebase-onboarding/SKILL.md +33 -0
- coderagent/skills/presets/data-analysis/SKILL.md +35 -0
- coderagent/skills/presets/deep-research/SKILL.md +38 -0
- coderagent/skills/presets/frontend-dev/SKILL.md +32 -0
- coderagent/skills/presets/long-document/SKILL.md +37 -0
- coderagent/skills/presets/long-document/scripts/pdf_text.py +37 -0
- coderagent/skills/presets/office-docx/SKILL.md +36 -0
- coderagent/skills/presets/office-docx/scripts/docx_text.py +36 -0
- coderagent/skills/presets/office-pptx/SKILL.md +32 -0
- coderagent/skills/presets/office-xlsx/SKILL.md +34 -0
- coderagent/skills/presets/office-xlsx/scripts/xlsx_text.py +72 -0
- coderagent/skills/presets/writing/SKILL.md +31 -0
- coderagent/skills/sandbox.py +269 -0
- coderagent/skills/sites.py +177 -0
- coderagent/skills/source.py +404 -0
- coderagent/testing/__init__.py +5 -0
- coderagent/testing/factory.py +59 -0
- coderagent/testing/scripted_model.py +54 -0
- coderagent/tools/__init__.py +1 -0
- coderagent/tools/base.py +54 -0
- coderagent/tools/bash_policy.py +486 -0
- coderagent/tools/builtin/__init__.py +35 -0
- coderagent/tools/builtin/fs.py +283 -0
- coderagent/tools/builtin/patch.py +279 -0
- coderagent/tools/builtin/search.py +242 -0
- coderagent/tools/builtin/shell.py +336 -0
- coderagent/tools/builtin/skill.py +41 -0
- coderagent/tools/builtin/task.py +53 -0
- coderagent/tools/builtin/todo.py +63 -0
- coderagent/tools/executor.py +243 -0
- coderagent/tools/mcp.py +317 -0
- coderagent/tools/permissions.py +472 -0
- coderagent/tools/registry.py +83 -0
- coderagent/tools/rules.py +138 -0
- coderagent/ui/__init__.py +1 -0
- coderagent/ui/cli.py +498 -0
- coderagent/ui/commands/__init__.py +109 -0
- coderagent/ui/commands/builtin.py +778 -0
- coderagent/ui/commands/compact.py +12 -0
- coderagent/ui/commands/resume.py +26 -0
- coderagent/ui/commands/review.py +73 -0
- coderagent/ui/commands/rewind.py +28 -0
- coderagent/ui/custom_commands.py +179 -0
- coderagent/ui/notify.py +46 -0
- coderagent/ui/open_file.py +48 -0
- coderagent/ui/render.py +62 -0
- coderagent/ui/spinner.py +68 -0
- coderagent/ui/tui.py +610 -0
- coderagent/ui/widgets/__init__.py +29 -0
- coderagent/ui/widgets/approval_prompt.py +129 -0
- coderagent/ui/widgets/diff_view.py +97 -0
- coderagent/ui/widgets/file_tree.py +105 -0
- coderagent/ui/widgets/markdown_message.py +44 -0
- coderagent/ui/widgets/markup.py +10 -0
- coderagent/ui/widgets/message_block.py +61 -0
- coderagent/ui/widgets/path_suggester.py +66 -0
- coderagent/ui/widgets/session_picker.py +49 -0
- coderagent/ui/widgets/status_bar.py +44 -0
- coderagent/ui/widgets/todo_panel.py +40 -0
- coderagent/ui/widgets/tool_card.py +104 -0
- coderagent/ui/widgets/working_dots.py +26 -0
- coderagent/version.py +7 -0
- coderagent/web/__init__.py +5 -0
- coderagent/web/api.py +449 -0
- coderagent/web/app.py +113 -0
- coderagent/web/approver.py +73 -0
- coderagent/web/config_api.py +53 -0
- coderagent/web/events.py +159 -0
- coderagent/web/files.py +115 -0
- coderagent/web/i18n.py +346 -0
- coderagent/web/server.py +100 -0
- coderagent/web/sessions.py +404 -0
- coderagent/web/skills_api.py +376 -0
- coderagent/web/static/app.css +283 -0
- coderagent/web/static/app.js +1466 -0
- coderagent/web/templates/en/base.html +31 -0
- coderagent/web/templates/en/chat.html +60 -0
- coderagent/web/templates/en/macros.html +9 -0
- coderagent/web/templates/en/settings.html +80 -0
- coderagent/web/templates/en/skills.html +64 -0
- coderagent/web/templates/zh/base.html +31 -0
- coderagent/web/templates/zh/chat.html +60 -0
- coderagent/web/templates/zh/macros.html +9 -0
- coderagent/web/templates/zh/settings.html +77 -0
- coderagent/web/templates/zh/skills.html +61 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Todo tool: the model keeps a visible task list in the session."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from coderagent.core.events import Event, EventType
|
|
7
|
+
from coderagent.tools.base import ToolContext, ToolResult
|
|
8
|
+
|
|
9
|
+
STATUSES = ("pending", "in_progress", "completed")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class TodoWriteTool:
|
|
13
|
+
name = "todo_write"
|
|
14
|
+
description = (
|
|
15
|
+
"Record the task list for the current work. Replaces the previous list. "
|
|
16
|
+
"Each item has `content`, `status` (pending, in_progress or completed) and an optional `activeForm`."
|
|
17
|
+
)
|
|
18
|
+
parameters = {
|
|
19
|
+
"type": "object",
|
|
20
|
+
"properties": {
|
|
21
|
+
"todos": {
|
|
22
|
+
"type": "array",
|
|
23
|
+
"description": "The full task list.",
|
|
24
|
+
"items": {
|
|
25
|
+
"type": "object",
|
|
26
|
+
"properties": {
|
|
27
|
+
"content": {"type": "string"},
|
|
28
|
+
"status": {"type": "string", "enum": list(STATUSES)},
|
|
29
|
+
"activeForm": {"type": "string"},
|
|
30
|
+
},
|
|
31
|
+
"required": ["content", "status"],
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
"required": ["todos"],
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
39
|
+
todos = params.get("todos")
|
|
40
|
+
if not isinstance(todos, list):
|
|
41
|
+
return ToolResult("Error: `todos` is required and must be an array.", is_error=True)
|
|
42
|
+
for index, todo in enumerate(todos):
|
|
43
|
+
if not isinstance(todo, dict):
|
|
44
|
+
return ToolResult(f"Error: todo #{index + 1} must be an object.", is_error=True)
|
|
45
|
+
if not isinstance(todo.get("content"), str) or not todo["content"].strip():
|
|
46
|
+
return ToolResult(f"Error: todo #{index + 1} needs a non-empty `content`.", is_error=True)
|
|
47
|
+
if todo.get("status") not in STATUSES:
|
|
48
|
+
return ToolResult(
|
|
49
|
+
f"Error: todo #{index + 1} has invalid status '{todo.get('status')}'. Use one of {', '.join(STATUSES)}.",
|
|
50
|
+
is_error=True,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
ctx.session.metadata["todos"] = todos
|
|
54
|
+
ctx.bus.publish(
|
|
55
|
+
Event(
|
|
56
|
+
type=EventType.TOOL_RESULT,
|
|
57
|
+
session_id=ctx.session.id,
|
|
58
|
+
timestamp=time.time(),
|
|
59
|
+
payload={"tool": self.name, "todos": todos},
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
done = sum(1 for todo in todos if todo["status"] == "completed")
|
|
63
|
+
return ToolResult(f"Task list updated ({done}/{len(todos)} completed).", metadata={"todos": todos})
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Executor: model tool calls -> permission check -> tool run -> observation messages."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
6
|
+
|
|
7
|
+
from coderagent.core.events import Event, EventType
|
|
8
|
+
from coderagent.core.redact import redact
|
|
9
|
+
from coderagent.core.session import SessionState
|
|
10
|
+
from coderagent.core.tokens import trim_text
|
|
11
|
+
from coderagent.tools.base import ToolContext, ToolResult
|
|
12
|
+
from coderagent.tools.permissions import (
|
|
13
|
+
WRITE_TOOLS,
|
|
14
|
+
ApprovalDecision,
|
|
15
|
+
Approver,
|
|
16
|
+
PermissionPolicy,
|
|
17
|
+
pattern_for,
|
|
18
|
+
)
|
|
19
|
+
from coderagent.tools.registry import ToolRegistry
|
|
20
|
+
|
|
21
|
+
SEQUENTIAL_TOOLS = {"bash", "write", "edit", "multi_edit", "apply_patch"}
|
|
22
|
+
|
|
23
|
+
MAX_PARALLEL_TOOLS = 8
|
|
24
|
+
"""How many tools may run at the same time.
|
|
25
|
+
|
|
26
|
+
A model that asks for a hundred reads does not get a hundred threads.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ToolExecutor:
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
registry: ToolRegistry,
|
|
34
|
+
policy: PermissionPolicy,
|
|
35
|
+
ctx_factory,
|
|
36
|
+
approver: Approver | None = None,
|
|
37
|
+
*,
|
|
38
|
+
rules_home=None,
|
|
39
|
+
on_path=None,
|
|
40
|
+
before_write=None,
|
|
41
|
+
hooks=None,
|
|
42
|
+
store=None,
|
|
43
|
+
) -> None:
|
|
44
|
+
self.registry = registry
|
|
45
|
+
self.policy = policy
|
|
46
|
+
self.ctx_factory = ctx_factory
|
|
47
|
+
self.approver = approver
|
|
48
|
+
self.rules_home = rules_home
|
|
49
|
+
self.on_path = on_path
|
|
50
|
+
"""Called with the path of every path based tool, so the engine can pick up instructions."""
|
|
51
|
+
self.before_write = before_write
|
|
52
|
+
"""Called with (tool, params) before a write tool runs, e.g. to take a checkpoint."""
|
|
53
|
+
self.hooks = hooks
|
|
54
|
+
"""The hook runner, when the session has hooks."""
|
|
55
|
+
self.store = store
|
|
56
|
+
"""The event log. The result of a tool is written to it, with its diff."""
|
|
57
|
+
|
|
58
|
+
def plan(self, actions: list[dict]) -> list[dict]:
|
|
59
|
+
"""Parse raw tool calls into normalized actions."""
|
|
60
|
+
planned = []
|
|
61
|
+
for call in actions:
|
|
62
|
+
function = call.get("function") or {}
|
|
63
|
+
name = function.get("name") or call.get("name") or ""
|
|
64
|
+
raw_arguments = function.get("arguments", call.get("arguments", "{}"))
|
|
65
|
+
action = {
|
|
66
|
+
"tool": name,
|
|
67
|
+
"tool_call_id": call.get("id", ""),
|
|
68
|
+
"args": {},
|
|
69
|
+
"raw": call,
|
|
70
|
+
}
|
|
71
|
+
if isinstance(raw_arguments, dict):
|
|
72
|
+
action["args"] = raw_arguments
|
|
73
|
+
else:
|
|
74
|
+
try:
|
|
75
|
+
parsed = json.loads(raw_arguments or "{}")
|
|
76
|
+
except json.JSONDecodeError as error:
|
|
77
|
+
action["error"] = (
|
|
78
|
+
f"Error: could not parse the arguments of '{name}' as JSON ({error}). "
|
|
79
|
+
"Send the arguments as a JSON object."
|
|
80
|
+
)
|
|
81
|
+
else:
|
|
82
|
+
if not isinstance(parsed, dict):
|
|
83
|
+
action["error"] = f"Error: the arguments of '{name}' must be a JSON object."
|
|
84
|
+
else:
|
|
85
|
+
action["args"] = parsed
|
|
86
|
+
planned.append(action)
|
|
87
|
+
return planned
|
|
88
|
+
|
|
89
|
+
def execute(self, actions: list[dict]) -> list[dict]:
|
|
90
|
+
"""Run the actions and return observation messages in input order."""
|
|
91
|
+
if not actions:
|
|
92
|
+
return []
|
|
93
|
+
ctx = self.ctx_factory()
|
|
94
|
+
prepared = [self._prepare(action, ctx) for action in actions]
|
|
95
|
+
if any(action["tool"] in SEQUENTIAL_TOOLS for action in prepared) or len(prepared) == 1:
|
|
96
|
+
return [self._run(action, ctx) for action in prepared]
|
|
97
|
+
with ThreadPoolExecutor(max_workers=min(len(prepared), MAX_PARALLEL_TOOLS)) as pool:
|
|
98
|
+
return list(pool.map(lambda action: self._run(action, ctx), prepared))
|
|
99
|
+
|
|
100
|
+
def _prepare(self, action: dict, ctx: ToolContext) -> dict:
|
|
101
|
+
"""Resolve permissions before running anything."""
|
|
102
|
+
if action.get("error"):
|
|
103
|
+
return action
|
|
104
|
+
tool = self.registry.get(action["tool"])
|
|
105
|
+
if tool is None:
|
|
106
|
+
action["error"] = (
|
|
107
|
+
f"Error: unknown tool '{action['tool']}'. Available tools: {', '.join(self.registry.names())}."
|
|
108
|
+
)
|
|
109
|
+
return action
|
|
110
|
+
if self.hooks:
|
|
111
|
+
hook = self.hooks.apply("PreToolUse", {"tool": action["tool"], "params": action["args"]})
|
|
112
|
+
if hook.blocked:
|
|
113
|
+
action["error"] = f"Error: the hook blocked '{action['tool']}'. {hook.reason}".strip()
|
|
114
|
+
return action
|
|
115
|
+
if isinstance(hook.updated_input, dict):
|
|
116
|
+
"""Only the arguments of a tool are a mapping. A prompt is not."""
|
|
117
|
+
action["args"] = hook.updated_input
|
|
118
|
+
decision = self.policy.evaluate(action["tool"], action["args"])
|
|
119
|
+
action["decision"] = decision
|
|
120
|
+
if decision.decision == "deny":
|
|
121
|
+
action["error"] = f"Error: permission denied for '{action['tool']}'. {decision.reason}".strip()
|
|
122
|
+
return action
|
|
123
|
+
if decision.decision == "ask":
|
|
124
|
+
approver = self.approver
|
|
125
|
+
if approver is None:
|
|
126
|
+
action["error"] = (
|
|
127
|
+
f"Error: '{action['tool']}' needs approval but no approver is available. "
|
|
128
|
+
"Run with --permission-mode bypass to allow it."
|
|
129
|
+
)
|
|
130
|
+
return action
|
|
131
|
+
answer = self._ask(action, ctx, approver, decision.reason)
|
|
132
|
+
if answer == ApprovalDecision.DENY:
|
|
133
|
+
action["error"] = f"Error: the user denied '{action['tool']}'. {decision.reason}".strip()
|
|
134
|
+
return action
|
|
135
|
+
if answer == ApprovalDecision.ALWAYS:
|
|
136
|
+
self._remember(action["tool"], action["args"])
|
|
137
|
+
return action
|
|
138
|
+
|
|
139
|
+
def _ask(self, action: dict, ctx: ToolContext, approver: Approver, reason: str) -> ApprovalDecision:
|
|
140
|
+
"""Ask a human. The session waits for the answer.
|
|
141
|
+
|
|
142
|
+
The request itself is published by the approver, which is the one that
|
|
143
|
+
talks to the interface. The executor only says what the session is doing.
|
|
144
|
+
"""
|
|
145
|
+
self._state(ctx, SessionState.AWAITING_APPROVAL)
|
|
146
|
+
answer = approver.request(action["tool"], action["args"], reason)
|
|
147
|
+
self._state(ctx, SessionState.EXECUTING)
|
|
148
|
+
return answer
|
|
149
|
+
|
|
150
|
+
def _remember(self, tool: str, params: dict) -> None:
|
|
151
|
+
"""Persist an 'always allow' decision in the user rule file."""
|
|
152
|
+
from coderagent.tools.rules import add_rule
|
|
153
|
+
|
|
154
|
+
add_rule(tool, pattern_for(tool, params), "allow", "always allowed by the user", self.rules_home)
|
|
155
|
+
|
|
156
|
+
def _run(self, action: dict, ctx: ToolContext) -> dict:
|
|
157
|
+
if action.get("error"):
|
|
158
|
+
return self._observation(action["tool_call_id"], action["error"])
|
|
159
|
+
if ctx.cancel is not None and ctx.cancel():
|
|
160
|
+
"""The turn was interrupted: the tool does not run at all."""
|
|
161
|
+
return self._observation(
|
|
162
|
+
action["tool_call_id"], "Error: the turn was interrupted, so the tool did not run."
|
|
163
|
+
)
|
|
164
|
+
tool = self.registry.get(action["tool"])
|
|
165
|
+
for path in self._paths_of(action):
|
|
166
|
+
if self.on_path:
|
|
167
|
+
self.on_path(path)
|
|
168
|
+
if action["tool"] in WRITE_TOOLS and self.before_write:
|
|
169
|
+
for path in self._paths_of(action):
|
|
170
|
+
self.before_write(action["tool"], {**action["args"], "path": path})
|
|
171
|
+
try:
|
|
172
|
+
result: ToolResult = tool.run(action["args"], ctx)
|
|
173
|
+
except Exception as e:
|
|
174
|
+
return self._observation(
|
|
175
|
+
action["tool_call_id"], f"Error: '{action['tool']}' failed: {type(e).__name__}: {e}"
|
|
176
|
+
)
|
|
177
|
+
if result.metadata.get("truncated"):
|
|
178
|
+
ctx.session.metadata.setdefault("truncated_outputs", []).append(result.metadata["truncated"])
|
|
179
|
+
content = trim_text(redact(result.content), ctx.config.max_output_tokens)[0]
|
|
180
|
+
"""Every tool result is cut to the budget of the context, not only the output of bash."""
|
|
181
|
+
is_error = result.is_error
|
|
182
|
+
if self.hooks:
|
|
183
|
+
hook = self.hooks.apply(
|
|
184
|
+
"PostToolUse", {"tool": action["tool"], "params": action["args"], "result": content}
|
|
185
|
+
)
|
|
186
|
+
if hook.blocked:
|
|
187
|
+
content = f"Error: the hook blocked '{action['tool']}'. {hook.reason}".strip()
|
|
188
|
+
is_error = True
|
|
189
|
+
if hook.additional_context:
|
|
190
|
+
content = f"{content}\n\n[hook] {hook.additional_context}"
|
|
191
|
+
self._publish(action, result, ctx, content, is_error)
|
|
192
|
+
return self._observation(action["tool_call_id"], content)
|
|
193
|
+
|
|
194
|
+
def _observation(self, tool_call_id: str, content: str) -> dict:
|
|
195
|
+
return {"role": "tool", "tool_call_id": tool_call_id, "content": content}
|
|
196
|
+
|
|
197
|
+
def _paths_of(self, action: dict) -> list[str]:
|
|
198
|
+
"""The files a tool is about to touch.
|
|
199
|
+
|
|
200
|
+
A tool that changes several files at once, like `apply_patch`, says which ones.
|
|
201
|
+
"""
|
|
202
|
+
path = action["args"].get("path")
|
|
203
|
+
if path:
|
|
204
|
+
return [str(path)]
|
|
205
|
+
tool = self.registry.get(action["tool"])
|
|
206
|
+
getter = getattr(tool, "touched_paths", None)
|
|
207
|
+
return list(getter(action["args"])) if getter else []
|
|
208
|
+
|
|
209
|
+
def _publish(self, action: dict, result: ToolResult, ctx: ToolContext, content: str, is_error: bool) -> None:
|
|
210
|
+
"""Put the result of a tool in the log.
|
|
211
|
+
|
|
212
|
+
The log holds what the model saw: the content is already cut to the
|
|
213
|
+
budget of the context, so a tool that prints a hundred megabytes does
|
|
214
|
+
not fill the store of the session.
|
|
215
|
+
"""
|
|
216
|
+
event = Event(
|
|
217
|
+
type=EventType.TOOL_RESULT,
|
|
218
|
+
session_id=ctx.session.id,
|
|
219
|
+
timestamp=time.time(),
|
|
220
|
+
payload={
|
|
221
|
+
"tool": action["tool"],
|
|
222
|
+
"tool_call_id": action["tool_call_id"],
|
|
223
|
+
"content": content,
|
|
224
|
+
"is_error": is_error,
|
|
225
|
+
"diff": redact(trim_text(result.metadata.get("diff", ""), ctx.config.max_output_tokens)[0]),
|
|
226
|
+
},
|
|
227
|
+
)
|
|
228
|
+
ctx.bus.publish(event)
|
|
229
|
+
if self.store is not None:
|
|
230
|
+
"""The log keeps the result, so that the replay shows the diff of the change."""
|
|
231
|
+
self.store.append(ctx.session.id, event)
|
|
232
|
+
|
|
233
|
+
def _state(self, ctx: ToolContext, state: SessionState) -> None:
|
|
234
|
+
"""The state of the session follows what the agent is doing."""
|
|
235
|
+
ctx.session.state = state
|
|
236
|
+
self._log(ctx, EventType.STATE_CHANGE, {"state": state.value})
|
|
237
|
+
|
|
238
|
+
def _log(self, ctx: ToolContext, event_type: EventType, payload: dict) -> None:
|
|
239
|
+
"""Put an event in the log of the session."""
|
|
240
|
+
event = Event(type=event_type, session_id=ctx.session.id, timestamp=time.time(), payload=payload)
|
|
241
|
+
ctx.bus.publish(event)
|
|
242
|
+
if self.store is not None:
|
|
243
|
+
self.store.append(ctx.session.id, event)
|
coderagent/tools/mcp.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""MCP: the tools of an MCP server, used like the built-in ones.
|
|
2
|
+
|
|
3
|
+
The MCP SDK is asynchronous, the agent is not. Every server therefore gets a
|
|
4
|
+
thread with its own event loop; the tools call into it and wait for the answer.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import shlex
|
|
11
|
+
import threading
|
|
12
|
+
from contextlib import AsyncExitStack
|
|
13
|
+
from typing import Any
|
|
14
|
+
from urllib.parse import urlparse
|
|
15
|
+
|
|
16
|
+
from coderagent.config.schema import MCPServerConfig
|
|
17
|
+
from coderagent.core.events import EventBus
|
|
18
|
+
from coderagent.tools.base import ToolContext, ToolResult
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger("coderagent.mcp")
|
|
21
|
+
|
|
22
|
+
TIMEOUT = 30.0
|
|
23
|
+
"""Seconds for a normal request of a server on an address."""
|
|
24
|
+
|
|
25
|
+
READ_TIMEOUT = 300.0
|
|
26
|
+
"""Seconds for a stream that stays open. The defaults of the MCP SDK."""
|
|
27
|
+
|
|
28
|
+
LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1")
|
|
29
|
+
"""The addresses that are on this machine."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def tool_name(server: str, tool: str) -> str:
|
|
33
|
+
"""The name a tool of a server gets: `mcp__<server>__<tool>`."""
|
|
34
|
+
return f"mcp__{server}__{tool}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class MCPTool:
|
|
38
|
+
"""A tool of an MCP server, seen from the agent."""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self, client: "MCPClient", name: str, remote: str, description: str, parameters: dict[str, Any]
|
|
42
|
+
) -> None:
|
|
43
|
+
self.client = client
|
|
44
|
+
self.name = name
|
|
45
|
+
self.remote = remote
|
|
46
|
+
"""The name the server knows the tool by."""
|
|
47
|
+
self.description = description
|
|
48
|
+
self.parameters = parameters
|
|
49
|
+
|
|
50
|
+
def run(self, params: dict[str, Any], ctx: ToolContext) -> ToolResult:
|
|
51
|
+
return self.client.call(self.remote, params)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class MCPClient:
|
|
55
|
+
"""One MCP server: the connection, its tools and the calls to them."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, config: MCPServerConfig, bus: EventBus | None = None, timeout: int = 30) -> None:
|
|
58
|
+
self.config = config
|
|
59
|
+
self.bus = bus
|
|
60
|
+
self.timeout = timeout
|
|
61
|
+
self.startup_timeout = config.startup_timeout or timeout
|
|
62
|
+
"""The seconds the server may take to start. The timeout of the section when it has none."""
|
|
63
|
+
self.tool_timeout = config.tool_timeout or timeout
|
|
64
|
+
"""The seconds one call may take. The timeout of the section when it has none."""
|
|
65
|
+
self._error = ""
|
|
66
|
+
"""Why the server is not available, when it is not."""
|
|
67
|
+
self._session = None
|
|
68
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
69
|
+
self._thread: threading.Thread | None = None
|
|
70
|
+
self._ready = threading.Event()
|
|
71
|
+
self._stop = threading.Event()
|
|
72
|
+
self._tools: list[MCPTool] = []
|
|
73
|
+
self._lock = None if config.supports_parallel_tool_calls else threading.Lock()
|
|
74
|
+
"""The lock of a server that takes one call at a time."""
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def tools(self) -> list[MCPTool]:
|
|
78
|
+
return self._tools
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def error(self) -> str:
|
|
82
|
+
"""Why the server is not available, when it is not."""
|
|
83
|
+
return self._error
|
|
84
|
+
|
|
85
|
+
def start(self) -> list[MCPTool]:
|
|
86
|
+
"""Connect to the server and return its tools. Never raises."""
|
|
87
|
+
self._thread = threading.Thread(target=self._run, daemon=True, name=f"mcp-{self.config.name}")
|
|
88
|
+
self._thread.start()
|
|
89
|
+
self._ready.wait(self.startup_timeout)
|
|
90
|
+
if self._error:
|
|
91
|
+
logger.warning("MCP server '%s' is not available: %s", self.config.name, self._error)
|
|
92
|
+
return self._tools
|
|
93
|
+
|
|
94
|
+
def stop(self) -> None:
|
|
95
|
+
"""Close the connection to the server."""
|
|
96
|
+
self._stop.set()
|
|
97
|
+
if self._loop is None:
|
|
98
|
+
return
|
|
99
|
+
try:
|
|
100
|
+
self._loop.call_soon_threadsafe(self._loop.stop)
|
|
101
|
+
except RuntimeError:
|
|
102
|
+
pass
|
|
103
|
+
|
|
104
|
+
def call(self, name: str, arguments: dict) -> ToolResult:
|
|
105
|
+
"""Call a tool of the server and turn its answer into a tool result.
|
|
106
|
+
|
|
107
|
+
A broken connection is tried once more with a new one.
|
|
108
|
+
"""
|
|
109
|
+
if self._lock is None:
|
|
110
|
+
return self._call_once(name, arguments)
|
|
111
|
+
with self._lock:
|
|
112
|
+
"""The server takes one call at a time, so the calls wait for each other."""
|
|
113
|
+
return self._call_once(name, arguments)
|
|
114
|
+
|
|
115
|
+
def _call_once(self, name: str, arguments: dict) -> ToolResult:
|
|
116
|
+
if self._session is None:
|
|
117
|
+
return ToolResult(content=f"Error: the MCP server '{self.config.name}' is not connected.", is_error=True)
|
|
118
|
+
try:
|
|
119
|
+
result = self._call_remote(name, arguments)
|
|
120
|
+
except Exception as e:
|
|
121
|
+
logger.warning("The MCP server '%s' broke: %s", self.config.name, e)
|
|
122
|
+
self._restart()
|
|
123
|
+
try:
|
|
124
|
+
result = self._call_remote(name, arguments)
|
|
125
|
+
except Exception as retry_error:
|
|
126
|
+
return ToolResult(
|
|
127
|
+
content=f"Error: the MCP tool '{name}' failed: {type(retry_error).__name__}: {retry_error}",
|
|
128
|
+
is_error=True,
|
|
129
|
+
)
|
|
130
|
+
return ToolResult(content=_content_text(result), is_error=bool(getattr(result, "isError", False)))
|
|
131
|
+
|
|
132
|
+
def _call_remote(self, name: str, arguments: dict):
|
|
133
|
+
return asyncio.run_coroutine_threadsafe(self._call(name, arguments), self._loop).result(self.tool_timeout)
|
|
134
|
+
|
|
135
|
+
def _restart(self) -> None:
|
|
136
|
+
"""Start over with a new connection."""
|
|
137
|
+
self.stop()
|
|
138
|
+
if self._thread is not None:
|
|
139
|
+
self._thread.join(timeout=self.startup_timeout)
|
|
140
|
+
self._thread = None
|
|
141
|
+
self._session = None
|
|
142
|
+
self._tools = []
|
|
143
|
+
self._error = ""
|
|
144
|
+
self._stop = threading.Event()
|
|
145
|
+
self._ready = threading.Event()
|
|
146
|
+
self.start()
|
|
147
|
+
|
|
148
|
+
async def _call(self, name: str, arguments: dict):
|
|
149
|
+
return await self._session.call_tool(name, arguments)
|
|
150
|
+
|
|
151
|
+
def _run(self) -> None:
|
|
152
|
+
try:
|
|
153
|
+
asyncio.run(self._main())
|
|
154
|
+
except Exception as e:
|
|
155
|
+
self._error = _describe(e)
|
|
156
|
+
logger.warning("MCP server '%s' failed: %s", self.config.name, self._error)
|
|
157
|
+
finally:
|
|
158
|
+
self._ready.set()
|
|
159
|
+
|
|
160
|
+
async def _main(self) -> None:
|
|
161
|
+
from mcp import ClientSession, StdioServerParameters
|
|
162
|
+
from mcp.client.stdio import stdio_client
|
|
163
|
+
|
|
164
|
+
self._loop = asyncio.get_running_loop()
|
|
165
|
+
if self.config.url and self.config.command:
|
|
166
|
+
raise ValueError("the MCP server has both a command and a url")
|
|
167
|
+
async with AsyncExitStack() as stack:
|
|
168
|
+
if self.config.url:
|
|
169
|
+
read, write = await self._http_streams(stack)
|
|
170
|
+
else:
|
|
171
|
+
command, args = _split_command(self.config.command)
|
|
172
|
+
params = StdioServerParameters(command=command, args=args, env=self.config.env or None)
|
|
173
|
+
read, write = await stack.enter_async_context(stdio_client(params))
|
|
174
|
+
self._session = await stack.enter_async_context(ClientSession(read, write))
|
|
175
|
+
await self._session.initialize()
|
|
176
|
+
self._tools = self._make_tools(await self._session.list_tools())
|
|
177
|
+
self._ready.set()
|
|
178
|
+
while not self._stop.is_set():
|
|
179
|
+
await asyncio.sleep(0.05)
|
|
180
|
+
|
|
181
|
+
async def _http_streams(self, stack: AsyncExitStack):
|
|
182
|
+
"""The streams of a server that listens on an address."""
|
|
183
|
+
from mcp.client.streamable_http import streamable_http_client
|
|
184
|
+
|
|
185
|
+
client = await stack.enter_async_context(self._http_client())
|
|
186
|
+
streams = await stack.enter_async_context(streamable_http_client(self.config.url, http_client=client))
|
|
187
|
+
return streams[0], streams[1]
|
|
188
|
+
|
|
189
|
+
def _http_client(self):
|
|
190
|
+
"""The http client of the server.
|
|
191
|
+
|
|
192
|
+
A server on this machine is not asked through the proxy of the system:
|
|
193
|
+
that proxy is there for the other hosts.
|
|
194
|
+
"""
|
|
195
|
+
import httpx2
|
|
196
|
+
|
|
197
|
+
return httpx2.AsyncClient(
|
|
198
|
+
headers=self.config.headers or None,
|
|
199
|
+
timeout=httpx2.Timeout(TIMEOUT, read=READ_TIMEOUT),
|
|
200
|
+
trust_env=not _is_local(self.config.url),
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
def _make_tools(self, listed) -> list[MCPTool]:
|
|
204
|
+
tools = []
|
|
205
|
+
for tool in listed.tools:
|
|
206
|
+
if not _wanted(self.config, tool.name):
|
|
207
|
+
"""The user hides some tools of this server. The model does not see them."""
|
|
208
|
+
continue
|
|
209
|
+
schema = getattr(tool, "input_schema", None) or getattr(tool, "inputSchema", None)
|
|
210
|
+
schema = schema or {"type": "object", "properties": {}}
|
|
211
|
+
tools.append(
|
|
212
|
+
MCPTool(
|
|
213
|
+
self,
|
|
214
|
+
tool_name(self.config.name, tool.name),
|
|
215
|
+
tool.name,
|
|
216
|
+
tool.description or f"The tool '{tool.name}' of the MCP server '{self.config.name}'.",
|
|
217
|
+
schema,
|
|
218
|
+
)
|
|
219
|
+
)
|
|
220
|
+
self._warn_unknown(listed.tools)
|
|
221
|
+
return tools
|
|
222
|
+
|
|
223
|
+
def _warn_unknown(self, listed) -> None:
|
|
224
|
+
"""Say when the user names a tool the server does not have.
|
|
225
|
+
|
|
226
|
+
A name that is wrong hides nothing and says nothing, so the user would
|
|
227
|
+
never learn that the tool they wanted is not there.
|
|
228
|
+
"""
|
|
229
|
+
names = {tool.name for tool in listed}
|
|
230
|
+
for name in (*self.config.enabled_tools, *self.config.disabled_tools):
|
|
231
|
+
if name != "*" and name not in names:
|
|
232
|
+
logger.warning(
|
|
233
|
+
"The MCP server '%s' has no tool '%s'. The name is ignored.",
|
|
234
|
+
self.config.name,
|
|
235
|
+
name,
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class MCPManager:
|
|
240
|
+
"""All the servers of the configuration."""
|
|
241
|
+
|
|
242
|
+
def __init__(self, config, bus: EventBus | None = None) -> None:
|
|
243
|
+
self.config = config
|
|
244
|
+
self.bus = bus
|
|
245
|
+
self.clients: list[MCPClient] = []
|
|
246
|
+
|
|
247
|
+
def start(self) -> list[MCPTool]:
|
|
248
|
+
"""Connect to every server and return the tools that work."""
|
|
249
|
+
tools: list[MCPTool] = []
|
|
250
|
+
for server in self.config.servers:
|
|
251
|
+
if not server.enabled or not (server.command or server.url):
|
|
252
|
+
continue
|
|
253
|
+
client = MCPClient(server, self.bus, self.config.timeout)
|
|
254
|
+
self.clients.append(client)
|
|
255
|
+
tools.extend(client.start())
|
|
256
|
+
return tools
|
|
257
|
+
|
|
258
|
+
def status(self) -> dict[str, str]:
|
|
259
|
+
"""The state of every server, by name."""
|
|
260
|
+
state = {
|
|
261
|
+
client.config.name: f"failed: {client.error}" if client.error else "connected" for client in self.clients
|
|
262
|
+
}
|
|
263
|
+
for server in self.config.servers:
|
|
264
|
+
state.setdefault(server.name, "no command and no url" if server.enabled else "disabled")
|
|
265
|
+
return state
|
|
266
|
+
|
|
267
|
+
def stop(self) -> None:
|
|
268
|
+
for client in self.clients:
|
|
269
|
+
client.stop()
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _wanted(config: MCPServerConfig, name: str) -> bool:
|
|
273
|
+
"""Whether the agent may call this tool of this server.
|
|
274
|
+
|
|
275
|
+
The list of the tools that are allowed comes first, the list of the tools
|
|
276
|
+
that are not comes after it. Both only take tools away.
|
|
277
|
+
"""
|
|
278
|
+
enabled = config.enabled_tools
|
|
279
|
+
disabled = config.disabled_tools
|
|
280
|
+
if enabled and "*" not in enabled and name not in enabled:
|
|
281
|
+
return False
|
|
282
|
+
return name not in disabled and "*" not in disabled
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _describe(error: BaseException) -> str:
|
|
286
|
+
"""The message of an error, with the errors of a group unwrapped."""
|
|
287
|
+
if hasattr(error, "exceptions"):
|
|
288
|
+
return ", ".join(_describe(sub) for sub in error.exceptions)
|
|
289
|
+
return f"{type(error).__name__}: {error}"
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _split_command(command: str) -> tuple[str, list[str]]:
|
|
293
|
+
parts = shlex.split(command)
|
|
294
|
+
if not parts:
|
|
295
|
+
raise ValueError("the MCP server has no command")
|
|
296
|
+
return parts[0], parts[1:]
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _is_local(url: str) -> bool:
|
|
300
|
+
"""Whether the address of a server is on this machine."""
|
|
301
|
+
return (urlparse(url).hostname or "") in LOCAL_HOSTS
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _content_text(result) -> str:
|
|
305
|
+
"""The content of an MCP answer, as text."""
|
|
306
|
+
parts = []
|
|
307
|
+
for item in getattr(result, "content", []) or []:
|
|
308
|
+
text = getattr(item, "text", None)
|
|
309
|
+
if text is not None:
|
|
310
|
+
parts.append(text)
|
|
311
|
+
continue
|
|
312
|
+
data = getattr(item, "data", None)
|
|
313
|
+
if data is not None:
|
|
314
|
+
parts.append(f"[{getattr(item, 'mimeType', 'binary')}] {len(data)} bytes")
|
|
315
|
+
continue
|
|
316
|
+
parts.append(json.dumps(item, default=str))
|
|
317
|
+
return "\n".join(parts)
|