rigcode 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.
- rigcode/__init__.py +4 -0
- rigcode/__main__.py +4 -0
- rigcode/agent/__init__.py +0 -0
- rigcode/agent/loop.py +627 -0
- rigcode/agent/mentions.py +70 -0
- rigcode/agent/prompts.py +195 -0
- rigcode/agent/runtime.py +535 -0
- rigcode/agent/session.py +165 -0
- rigcode/agent/state.py +161 -0
- rigcode/cli.py +283 -0
- rigcode/config.py +284 -0
- rigcode/doctor.py +158 -0
- rigcode/extensions.py +275 -0
- rigcode/hooks.py +142 -0
- rigcode/llm/__init__.py +0 -0
- rigcode/llm/client.py +259 -0
- rigcode/llm/probe.py +229 -0
- rigcode/llm/stream.py +240 -0
- rigcode/llm/textmode.py +161 -0
- rigcode/llm/types.py +92 -0
- rigcode/llm/wire.py +76 -0
- rigcode/mcp.py +329 -0
- rigcode/permissions.py +221 -0
- rigcode/prompts/agents/coder.md +13 -0
- rigcode/prompts/agents/debugger.md +14 -0
- rigcode/prompts/agents/explore.md +22 -0
- rigcode/prompts/agents/plan.md +21 -0
- rigcode/prompts/agents/researcher.md +14 -0
- rigcode/prompts/agents/reviewer.md +18 -0
- rigcode/prompts/agents/verifier.md +15 -0
- rigcode/prompts/commit.md +5 -0
- rigcode/prompts/compact.md +24 -0
- rigcode/prompts/init.md +10 -0
- rigcode/prompts/system.md +27 -0
- rigcode/tools/__init__.py +0 -0
- rigcode/tools/base.py +245 -0
- rigcode/tools/bashsafety.py +262 -0
- rigcode/tools/editmatch.py +367 -0
- rigcode/tools/files.py +534 -0
- rigcode/tools/interact.py +69 -0
- rigcode/tools/search.py +309 -0
- rigcode/tools/shell.py +424 -0
- rigcode/tools/skill.py +37 -0
- rigcode/tools/task.py +54 -0
- rigcode/tools/todo.py +62 -0
- rigcode/tools/web.py +346 -0
- rigcode/ui/__init__.py +0 -0
- rigcode/ui/base.py +69 -0
- rigcode/ui/commands.py +581 -0
- rigcode/ui/plain.py +321 -0
- rigcode/ui/render.py +207 -0
- rigcode/ui/terminal.py +1154 -0
- rigcode/utils/__init__.py +0 -0
- rigcode/utils/files.py +176 -0
- rigcode/utils/frontmatter.py +38 -0
- rigcode/utils/globmatch.py +91 -0
- rigcode/utils/jsonrepair.py +110 -0
- rigcode/utils/paths.py +83 -0
- rigcode/utils/text.py +105 -0
- rigcode-0.1.0.dist-info/METADATA +203 -0
- rigcode-0.1.0.dist-info/RECORD +64 -0
- rigcode-0.1.0.dist-info/WHEEL +4 -0
- rigcode-0.1.0.dist-info/entry_points.txt +2 -0
- rigcode-0.1.0.dist-info/licenses/LICENSE +21 -0
rigcode/llm/types.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Core LLM data types shared by the client, agent loop and UI."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class ToolCall:
|
|
9
|
+
id: str
|
|
10
|
+
name: str
|
|
11
|
+
arguments: str = "" # raw JSON text as produced by the model
|
|
12
|
+
args: dict | None = None # parsed arguments (None if unparseable)
|
|
13
|
+
error: str | None = None # parse/validation problem to report back
|
|
14
|
+
|
|
15
|
+
def to_openai(self) -> dict:
|
|
16
|
+
return {
|
|
17
|
+
"id": self.id,
|
|
18
|
+
"type": "function",
|
|
19
|
+
"function": {"name": self.name, "arguments": self.arguments or "{}"},
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Usage:
|
|
25
|
+
prompt_tokens: int = 0
|
|
26
|
+
completion_tokens: int = 0
|
|
27
|
+
cached_tokens: int = 0 # prompt tokens served from the server's KV cache
|
|
28
|
+
prompt_ms: float = 0.0
|
|
29
|
+
gen_ms: float = 0.0
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def gen_tps(self) -> float | None:
|
|
33
|
+
if self.gen_ms > 0 and self.completion_tokens:
|
|
34
|
+
return self.completion_tokens / (self.gen_ms / 1000)
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
@property
|
|
38
|
+
def prompt_tps(self) -> float | None:
|
|
39
|
+
processed = self.prompt_tokens - self.cached_tokens
|
|
40
|
+
if self.prompt_ms > 0 and processed > 0:
|
|
41
|
+
return processed / (self.prompt_ms / 1000)
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
def add(self, other: Usage) -> None:
|
|
45
|
+
self.prompt_tokens += other.prompt_tokens
|
|
46
|
+
self.completion_tokens += other.completion_tokens
|
|
47
|
+
self.cached_tokens += other.cached_tokens
|
|
48
|
+
self.prompt_ms += other.prompt_ms
|
|
49
|
+
self.gen_ms += other.gen_ms
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class AssistantTurn:
|
|
54
|
+
content: str = ""
|
|
55
|
+
reasoning: str = ""
|
|
56
|
+
tool_calls: list[ToolCall] = field(default_factory=list)
|
|
57
|
+
finish_reason: str | None = None
|
|
58
|
+
usage: Usage = field(default_factory=Usage)
|
|
59
|
+
interrupted: bool = False
|
|
60
|
+
elapsed: float = 0.0
|
|
61
|
+
first_token_latency: float | None = None
|
|
62
|
+
|
|
63
|
+
def to_message(self) -> dict:
|
|
64
|
+
msg: dict = {"role": "assistant", "content": self.content}
|
|
65
|
+
if self.reasoning:
|
|
66
|
+
msg["reasoning_content"] = self.reasoning
|
|
67
|
+
if self.tool_calls:
|
|
68
|
+
msg["tool_calls"] = [tc.to_openai() for tc in self.tool_calls]
|
|
69
|
+
return msg
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class Delta:
|
|
74
|
+
"""A streaming event from the model.
|
|
75
|
+
|
|
76
|
+
kind: reasoning | content | tool_start | tool_args | progress | reset | first_token
|
|
77
|
+
"""
|
|
78
|
+
kind: str
|
|
79
|
+
text: str = ""
|
|
80
|
+
index: int = 0
|
|
81
|
+
name: str | None = None
|
|
82
|
+
data: dict | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class LLMError(Exception):
|
|
86
|
+
def __init__(self, message: str, *, status: int | None = None, kind: str = "error",
|
|
87
|
+
body: str | None = None, retryable: bool = False):
|
|
88
|
+
super().__init__(message)
|
|
89
|
+
self.status = status
|
|
90
|
+
self.kind = kind
|
|
91
|
+
self.body = body
|
|
92
|
+
self.retryable = retryable
|
rigcode/llm/wire.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Convert the stored conversation into request messages.
|
|
2
|
+
|
|
3
|
+
History is always stored in OpenAI chat format with structured tool calls.
|
|
4
|
+
This module renders it for the active tool mode. The conversion is
|
|
5
|
+
deterministic so the server's prompt (KV) cache keeps matching the prefix.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
from rigcode.llm.textmode import render_tool_call_text, render_tool_result_text
|
|
12
|
+
from rigcode.llm.types import ToolCall
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _last_user_index(messages: list[dict]) -> int:
|
|
16
|
+
for i in range(len(messages) - 1, -1, -1):
|
|
17
|
+
if messages[i].get("role") == "user" and not messages[i].get("_tool_results"):
|
|
18
|
+
return i
|
|
19
|
+
return -1
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def to_wire(messages: list[dict], *, tool_mode: str = "native", keep_reasoning: str = "all") -> list[dict]:
|
|
23
|
+
last_user = _last_user_index(messages)
|
|
24
|
+
out: list[dict] = []
|
|
25
|
+
pending_text_results: list[str] = []
|
|
26
|
+
|
|
27
|
+
def flush_text_results() -> None:
|
|
28
|
+
if pending_text_results:
|
|
29
|
+
out.append({"role": "user", "content": "\n\n".join(pending_text_results)})
|
|
30
|
+
pending_text_results.clear()
|
|
31
|
+
|
|
32
|
+
for i, msg in enumerate(messages):
|
|
33
|
+
role = msg.get("role")
|
|
34
|
+
if role == "tool":
|
|
35
|
+
if tool_mode == "text":
|
|
36
|
+
pending_text_results.append(
|
|
37
|
+
render_tool_result_text(msg.get("name", "tool"), msg.get("tool_call_id", ""), _text(msg.get("content")))
|
|
38
|
+
)
|
|
39
|
+
else:
|
|
40
|
+
out.append({"role": "tool", "tool_call_id": msg.get("tool_call_id", ""), "content": msg.get("content") or ""})
|
|
41
|
+
continue
|
|
42
|
+
flush_text_results()
|
|
43
|
+
if role == "assistant":
|
|
44
|
+
wire: dict = {"role": "assistant", "content": msg.get("content") or ""}
|
|
45
|
+
reasoning = msg.get("reasoning_content")
|
|
46
|
+
if reasoning and (keep_reasoning == "all" or (keep_reasoning == "turn" and i > last_user)):
|
|
47
|
+
wire["reasoning_content"] = reasoning
|
|
48
|
+
calls = msg.get("tool_calls") or []
|
|
49
|
+
if calls:
|
|
50
|
+
if tool_mode == "text":
|
|
51
|
+
rendered = []
|
|
52
|
+
for c in calls:
|
|
53
|
+
fn = c.get("function", {})
|
|
54
|
+
raw = fn.get("arguments") or "{}"
|
|
55
|
+
try:
|
|
56
|
+
args = json.loads(raw)
|
|
57
|
+
except (json.JSONDecodeError, TypeError):
|
|
58
|
+
args = None
|
|
59
|
+
rendered.append(render_tool_call_text(ToolCall(id=c.get("id", ""), name=fn.get("name", ""),
|
|
60
|
+
arguments=raw, args=args)))
|
|
61
|
+
wire["content"] = (wire["content"] + "\n\n" if wire["content"] else "") + "\n".join(rendered)
|
|
62
|
+
else:
|
|
63
|
+
wire["tool_calls"] = calls
|
|
64
|
+
out.append(wire)
|
|
65
|
+
else:
|
|
66
|
+
out.append({"role": role, "content": msg.get("content") if msg.get("content") is not None else ""})
|
|
67
|
+
flush_text_results()
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _text(content) -> str:
|
|
72
|
+
if isinstance(content, str):
|
|
73
|
+
return content
|
|
74
|
+
if isinstance(content, list):
|
|
75
|
+
return "\n".join(p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text")
|
|
76
|
+
return str(content or "")
|
rigcode/mcp.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""Minimal Model Context Protocol client (stdio and Streamable HTTP transports).
|
|
2
|
+
|
|
3
|
+
Config (settings "mcp_servers" or a Claude-Code-style .mcp.json "mcpServers"):
|
|
4
|
+
"files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], "env": {}}
|
|
5
|
+
"remote": {"type": "http", "url": "https://example.com/mcp", "headers": {"Authorization": "Bearer ..."}}
|
|
6
|
+
Tools are exposed to the model as mcp__<server>__<tool>.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import shutil
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import httpx
|
|
19
|
+
|
|
20
|
+
from rigcode import __version__
|
|
21
|
+
from rigcode.llm.stream import SSEDecoder
|
|
22
|
+
from rigcode.tools.base import Tool, ToolContext, ToolResult
|
|
23
|
+
from rigcode.utils.text import truncate_middle
|
|
24
|
+
|
|
25
|
+
PROTOCOL_VERSION = "2025-06-18"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class McpError(Exception):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _sanitize(name: str) -> str:
|
|
33
|
+
return re.sub(r"[^A-Za-z0-9_-]", "_", name)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _StdioTransport:
|
|
37
|
+
def __init__(self, command: str, args: list[str], env: dict, cwd: Path):
|
|
38
|
+
self.command, self.args, self.env, self.cwd = command, args, env, cwd
|
|
39
|
+
self.proc: asyncio.subprocess.Process | None = None
|
|
40
|
+
self.stderr_tail: list[str] = []
|
|
41
|
+
self._handler = None
|
|
42
|
+
|
|
43
|
+
async def start(self, on_message) -> None:
|
|
44
|
+
exe = shutil.which(self.command) or self.command
|
|
45
|
+
env = {**os.environ, **{k: str(v) for k, v in (self.env or {}).items()}}
|
|
46
|
+
self.proc = await asyncio.create_subprocess_exec(
|
|
47
|
+
exe, *self.args, cwd=str(self.cwd), env=env, stdin=asyncio.subprocess.PIPE,
|
|
48
|
+
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, limit=16 * 1024 * 1024)
|
|
49
|
+
self._handler = on_message
|
|
50
|
+
asyncio.create_task(self._read_stdout())
|
|
51
|
+
asyncio.create_task(self._read_stderr())
|
|
52
|
+
|
|
53
|
+
async def _read_stdout(self) -> None:
|
|
54
|
+
assert self.proc and self.proc.stdout
|
|
55
|
+
while True:
|
|
56
|
+
line = await self.proc.stdout.readline()
|
|
57
|
+
if not line:
|
|
58
|
+
break
|
|
59
|
+
text = line.decode("utf-8", errors="replace").strip()
|
|
60
|
+
if not text:
|
|
61
|
+
continue
|
|
62
|
+
try:
|
|
63
|
+
msg = json.loads(text)
|
|
64
|
+
except json.JSONDecodeError:
|
|
65
|
+
self.stderr_tail.append(f"(non-JSON stdout) {text[:200]}")
|
|
66
|
+
continue
|
|
67
|
+
await self._handler(msg)
|
|
68
|
+
|
|
69
|
+
async def _read_stderr(self) -> None:
|
|
70
|
+
assert self.proc and self.proc.stderr
|
|
71
|
+
while True:
|
|
72
|
+
line = await self.proc.stderr.readline()
|
|
73
|
+
if not line:
|
|
74
|
+
break
|
|
75
|
+
self.stderr_tail.append(line.decode("utf-8", errors="replace").rstrip())
|
|
76
|
+
del self.stderr_tail[:-30]
|
|
77
|
+
|
|
78
|
+
async def send(self, msg: dict) -> dict | None:
|
|
79
|
+
if not self.proc or not self.proc.stdin or self.proc.returncode is not None:
|
|
80
|
+
raise McpError("server process is not running" + self._stderr_hint())
|
|
81
|
+
self.proc.stdin.write((json.dumps(msg) + "\n").encode("utf-8"))
|
|
82
|
+
await self.proc.stdin.drain()
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
def _stderr_hint(self) -> str:
|
|
86
|
+
return (": " + " | ".join(self.stderr_tail[-3:])) if self.stderr_tail else ""
|
|
87
|
+
|
|
88
|
+
async def close(self) -> None:
|
|
89
|
+
if self.proc and self.proc.returncode is None:
|
|
90
|
+
try:
|
|
91
|
+
self.proc.stdin.close() # type: ignore[union-attr]
|
|
92
|
+
await asyncio.wait_for(self.proc.wait(), 3)
|
|
93
|
+
except (asyncio.TimeoutError, OSError, AttributeError):
|
|
94
|
+
try:
|
|
95
|
+
self.proc.kill()
|
|
96
|
+
except OSError:
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class _HttpTransport:
|
|
101
|
+
def __init__(self, url: str, headers: dict):
|
|
102
|
+
self.url = url
|
|
103
|
+
self.headers = dict(headers or {})
|
|
104
|
+
self.session_id: str | None = None
|
|
105
|
+
self.client = httpx.AsyncClient(timeout=httpx.Timeout(connect=15, read=300, write=60, pool=30))
|
|
106
|
+
self._handler = None
|
|
107
|
+
self.stderr_tail: list[str] = []
|
|
108
|
+
|
|
109
|
+
async def start(self, on_message) -> None:
|
|
110
|
+
self._handler = on_message
|
|
111
|
+
|
|
112
|
+
async def send(self, msg: dict) -> dict | None:
|
|
113
|
+
headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
|
|
114
|
+
**self.headers}
|
|
115
|
+
if self.session_id:
|
|
116
|
+
headers["Mcp-Session-Id"] = self.session_id
|
|
117
|
+
if msg.get("method") != "initialize":
|
|
118
|
+
headers["MCP-Protocol-Version"] = PROTOCOL_VERSION
|
|
119
|
+
async with self.client.stream("POST", self.url, json=msg, headers=headers) as r:
|
|
120
|
+
if r.headers.get("mcp-session-id"):
|
|
121
|
+
self.session_id = r.headers["mcp-session-id"]
|
|
122
|
+
if r.status_code == 202 or "id" not in msg:
|
|
123
|
+
return None
|
|
124
|
+
if r.status_code >= 400:
|
|
125
|
+
body = (await r.aread()).decode("utf-8", errors="replace")[:300]
|
|
126
|
+
raise McpError(f"HTTP {r.status_code}: {body}")
|
|
127
|
+
ctype = r.headers.get("content-type", "")
|
|
128
|
+
if "text/event-stream" in ctype:
|
|
129
|
+
decoder = SSEDecoder()
|
|
130
|
+
async for line in r.aiter_lines():
|
|
131
|
+
frame = decoder.feed_line(line)
|
|
132
|
+
if frame is None:
|
|
133
|
+
continue
|
|
134
|
+
try:
|
|
135
|
+
data = json.loads(frame[1])
|
|
136
|
+
except json.JSONDecodeError:
|
|
137
|
+
continue
|
|
138
|
+
if data.get("id") == msg["id"] and ("result" in data or "error" in data):
|
|
139
|
+
return data
|
|
140
|
+
await self._handler(data)
|
|
141
|
+
return None
|
|
142
|
+
return json.loads((await r.aread()).decode("utf-8"))
|
|
143
|
+
|
|
144
|
+
async def close(self) -> None:
|
|
145
|
+
await self.client.aclose()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@dataclass
|
|
149
|
+
class McpServer:
|
|
150
|
+
name: str
|
|
151
|
+
spec: dict
|
|
152
|
+
cwd: Path
|
|
153
|
+
status: str = "pending" # pending | connected | failed
|
|
154
|
+
error: str | None = None
|
|
155
|
+
tools: list[dict] = field(default_factory=list)
|
|
156
|
+
server_info: dict = field(default_factory=dict)
|
|
157
|
+
|
|
158
|
+
def __post_init__(self) -> None:
|
|
159
|
+
self._next_id = 0
|
|
160
|
+
self._pending: dict[int, asyncio.Future] = {}
|
|
161
|
+
kind = str(self.spec.get("type") or ("http" if self.spec.get("url") else "stdio")).lower()
|
|
162
|
+
if kind in ("http", "streamable-http", "streamable_http"):
|
|
163
|
+
self.transport = _HttpTransport(self.spec["url"], self.spec.get("headers") or {})
|
|
164
|
+
elif kind == "stdio":
|
|
165
|
+
self.transport = _StdioTransport(self.spec.get("command", ""), [str(a) for a in self.spec.get("args") or []],
|
|
166
|
+
self.spec.get("env") or {}, self.cwd)
|
|
167
|
+
else:
|
|
168
|
+
raise McpError(f"unsupported MCP transport type '{kind}' (use stdio or http)")
|
|
169
|
+
|
|
170
|
+
async def _on_message(self, msg: dict) -> None:
|
|
171
|
+
if "id" in msg and ("result" in msg or "error" in msg) and msg.get("method") is None:
|
|
172
|
+
fut = self._pending.pop(msg["id"], None)
|
|
173
|
+
if fut and not fut.done():
|
|
174
|
+
fut.set_result(msg)
|
|
175
|
+
return
|
|
176
|
+
method = msg.get("method")
|
|
177
|
+
if method and "id" in msg: # server -> client request
|
|
178
|
+
if method == "ping":
|
|
179
|
+
result = {}
|
|
180
|
+
elif method == "roots/list":
|
|
181
|
+
result = {"roots": [{"uri": self.cwd.as_uri(), "name": self.cwd.name}]}
|
|
182
|
+
else:
|
|
183
|
+
await self.transport.send({"jsonrpc": "2.0", "id": msg["id"],
|
|
184
|
+
"error": {"code": -32601, "message": f"{method} not supported"}})
|
|
185
|
+
return
|
|
186
|
+
await self.transport.send({"jsonrpc": "2.0", "id": msg["id"], "result": result})
|
|
187
|
+
|
|
188
|
+
async def request(self, method: str, params: dict | None = None, timeout: float = 60) -> dict:
|
|
189
|
+
self._next_id += 1
|
|
190
|
+
rid = self._next_id
|
|
191
|
+
msg = {"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}}
|
|
192
|
+
fut = asyncio.get_running_loop().create_future()
|
|
193
|
+
self._pending[rid] = fut
|
|
194
|
+
direct = await self.transport.send(msg)
|
|
195
|
+
if direct is not None:
|
|
196
|
+
self._pending.pop(rid, None)
|
|
197
|
+
reply = direct
|
|
198
|
+
else:
|
|
199
|
+
try:
|
|
200
|
+
reply = await asyncio.wait_for(fut, timeout)
|
|
201
|
+
except asyncio.TimeoutError as e:
|
|
202
|
+
self._pending.pop(rid, None)
|
|
203
|
+
raise McpError(f"{method} timed out after {timeout:.0f}s") from e
|
|
204
|
+
if "error" in reply:
|
|
205
|
+
err = reply["error"]
|
|
206
|
+
raise McpError(f"{method}: {err.get('message', err)}")
|
|
207
|
+
return reply.get("result") or {}
|
|
208
|
+
|
|
209
|
+
async def connect(self, timeout: float = 30) -> None:
|
|
210
|
+
try:
|
|
211
|
+
await self.transport.start(self._on_message)
|
|
212
|
+
init = await self.request("initialize", {
|
|
213
|
+
"protocolVersion": PROTOCOL_VERSION, "capabilities": {"roots": {"listChanged": False}},
|
|
214
|
+
"clientInfo": {"name": "rigcode", "version": __version__}}, timeout=timeout)
|
|
215
|
+
self.server_info = init.get("serverInfo") or {}
|
|
216
|
+
await self.transport.send({"jsonrpc": "2.0", "method": "notifications/initialized"})
|
|
217
|
+
tools, cursor = [], None
|
|
218
|
+
for _ in range(20):
|
|
219
|
+
res = await self.request("tools/list", {"cursor": cursor} if cursor else {}, timeout=timeout)
|
|
220
|
+
tools.extend(res.get("tools") or [])
|
|
221
|
+
cursor = res.get("nextCursor")
|
|
222
|
+
if not cursor:
|
|
223
|
+
break
|
|
224
|
+
self.tools = tools
|
|
225
|
+
self.status = "connected"
|
|
226
|
+
except (McpError, OSError, httpx.HTTPError, KeyError) as e:
|
|
227
|
+
self.status = "failed"
|
|
228
|
+
hint = ""
|
|
229
|
+
if isinstance(self.transport, _StdioTransport) and self.transport.stderr_tail:
|
|
230
|
+
hint = " | " + " | ".join(self.transport.stderr_tail[-3:])
|
|
231
|
+
self.error = f"{type(e).__name__}: {e}{hint}"
|
|
232
|
+
|
|
233
|
+
async def call_tool(self, name: str, arguments: dict, timeout: float = 600) -> dict:
|
|
234
|
+
return await self.request("tools/call", {"name": name, "arguments": arguments}, timeout=timeout)
|
|
235
|
+
|
|
236
|
+
async def close(self) -> None:
|
|
237
|
+
await self.transport.close()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class McpTool(Tool):
|
|
241
|
+
kind = "mcp"
|
|
242
|
+
|
|
243
|
+
def __init__(self, server: McpServer, tool: dict):
|
|
244
|
+
self.server = server
|
|
245
|
+
self.tool_name = tool["name"]
|
|
246
|
+
self.name = f"mcp__{_sanitize(server.name)}__{_sanitize(tool['name'])}"[:64]
|
|
247
|
+
self.description = (tool.get("description") or f"MCP tool {tool['name']} from {server.name}").strip()[:1200]
|
|
248
|
+
schema = tool.get("inputSchema") or {"type": "object", "properties": {}}
|
|
249
|
+
if schema.get("type") != "object":
|
|
250
|
+
schema = {"type": "object", "properties": {}}
|
|
251
|
+
self.parameters = schema
|
|
252
|
+
self.read_only = bool((tool.get("annotations") or {}).get("readOnlyHint"))
|
|
253
|
+
|
|
254
|
+
def permission_target(self, args: dict) -> str:
|
|
255
|
+
return json.dumps(args, ensure_ascii=False)[:200]
|
|
256
|
+
|
|
257
|
+
def label(self, args: dict, ctx=None) -> str:
|
|
258
|
+
return f"{self.server.name}:{self.tool_name}({json.dumps(args, ensure_ascii=False)[:60]})"
|
|
259
|
+
|
|
260
|
+
async def run(self, args: dict, ctx: ToolContext) -> ToolResult:
|
|
261
|
+
if self.server.status != "connected":
|
|
262
|
+
return ToolResult.error(f"MCP server '{self.server.name}' is not connected: {self.server.error}")
|
|
263
|
+
try:
|
|
264
|
+
result = await self.server.call_tool(self.tool_name, args)
|
|
265
|
+
except McpError as e:
|
|
266
|
+
return ToolResult.error(f"MCP call failed: {e}")
|
|
267
|
+
parts = []
|
|
268
|
+
for item in result.get("content") or []:
|
|
269
|
+
t = item.get("type")
|
|
270
|
+
if t == "text":
|
|
271
|
+
parts.append(item.get("text", ""))
|
|
272
|
+
elif t == "resource":
|
|
273
|
+
res = item.get("resource") or {}
|
|
274
|
+
parts.append(res.get("text") or f"[resource {res.get('uri', '')}]")
|
|
275
|
+
elif t == "resource_link":
|
|
276
|
+
parts.append(f"[resource link: {item.get('uri', '')}]")
|
|
277
|
+
elif t in ("image", "audio"):
|
|
278
|
+
parts.append(f"[{t} content omitted ({item.get('mimeType', '')})]")
|
|
279
|
+
if not parts and result.get("structuredContent") is not None:
|
|
280
|
+
parts.append(json.dumps(result["structuredContent"], ensure_ascii=False, indent=2))
|
|
281
|
+
text = "\n".join(parts) or "(no content)"
|
|
282
|
+
limit = int(ctx.rt.settings.get("context.max_tool_output_chars", 12000))
|
|
283
|
+
text, _ = truncate_middle(text, limit)
|
|
284
|
+
return ToolResult(content=text, is_error=bool(result.get("isError")),
|
|
285
|
+
summary=f"{self.server.name}:{self.tool_name}")
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class McpManager:
|
|
289
|
+
def __init__(self, config: dict, cwd: Path):
|
|
290
|
+
self.servers: dict[str, McpServer] = {}
|
|
291
|
+
for name, spec in (config or {}).items():
|
|
292
|
+
if not isinstance(spec, dict) or spec.get("disabled"):
|
|
293
|
+
continue
|
|
294
|
+
try:
|
|
295
|
+
self.servers[name] = McpServer(name, spec, cwd)
|
|
296
|
+
except (McpError, KeyError) as e:
|
|
297
|
+
srv = McpServer.__new__(McpServer)
|
|
298
|
+
srv.name, srv.spec, srv.cwd, srv.status, srv.error, srv.tools, srv.server_info = \
|
|
299
|
+
name, spec, cwd, "failed", str(e), [], {}
|
|
300
|
+
self.servers[name] = srv
|
|
301
|
+
|
|
302
|
+
async def start_all(self, timeout: float = 30) -> None:
|
|
303
|
+
pending = [s for s in self.servers.values() if s.status == "pending"]
|
|
304
|
+
if pending:
|
|
305
|
+
await asyncio.gather(*(s.connect(timeout) for s in pending))
|
|
306
|
+
|
|
307
|
+
def tools(self) -> list[McpTool]:
|
|
308
|
+
out = []
|
|
309
|
+
for s in self.servers.values():
|
|
310
|
+
if s.status == "connected":
|
|
311
|
+
out.extend(McpTool(s, t) for t in s.tools if t.get("name"))
|
|
312
|
+
return out
|
|
313
|
+
|
|
314
|
+
def status_lines(self) -> list[str]:
|
|
315
|
+
lines = []
|
|
316
|
+
for s in self.servers.values():
|
|
317
|
+
if s.status == "connected":
|
|
318
|
+
lines.append(f"{s.name}: connected, {len(s.tools)} tools")
|
|
319
|
+
else:
|
|
320
|
+
lines.append(f"{s.name}: {s.status}" + (f" - {s.error}" if s.error else ""))
|
|
321
|
+
return lines
|
|
322
|
+
|
|
323
|
+
async def close_all(self) -> None:
|
|
324
|
+
for s in self.servers.values():
|
|
325
|
+
if hasattr(s, "transport"):
|
|
326
|
+
try:
|
|
327
|
+
await s.close()
|
|
328
|
+
except Exception: # noqa: BLE001
|
|
329
|
+
pass
|