Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ LLM_API_BASE=https://api.deepseek.com/v1
# BASH_MAX_OUTPUT=50000 # max bash output chars
# TOOL_RESULT_LIMIT=16000 # max tool result chars fed to LLM
# MAX_CONTEXT_MESSAGES=20 # auto-compress after this many messages
# MINIAGENT_CONTEXT_BUDGET=32768 # new runtime: conservative budget including tool schemas
# CONFIRM_DANGEROUS=true # confirm rm -rf, sudo, etc.
# MINIAGENT_STREAM=1 # 1=streaming on, 0=off
# MINIAGENT_HOME=~/.miniagent # session memory storage path
Expand Down
6 changes: 6 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@

## [Unreleased]

- [修复] MCP 工具路由绑定注册名称,入参不能覆盖审批和 Skill 白名单对应的远端工具。

- [新功能] JSONL 会话恢复、系统写入锁、不确定工具结果人工解决及保留原记录的上下文摘要。

- [修复] CLI 不再重复注入当前用户消息,日志不再输出 API Key 前缀。
- [改进] 默认 CLI 工具限制为 Coding Tools;原有基础工具保持显式可用。
- [文档] 记录六阶段迁移、权限边界和可复现源码统计。
- [新功能] 异步 Harness、实例级工具、静态插件生命周期和统一授权入口。
- [改进] Python 最低版本提升至 3.11,打包元数据统一到 pyproject.toml。
- [新功能] any-llm 异步模型适配、自定义 Provider、完整流式工具组装及 Provider 密钥隔离。
- [新功能] 简化 SKILL.md 读取与可恢复工具白名单,官方 MCP 2.3 stdio 插件。
- [改进] 移除手写 MCP 传输;旧隐式进程 API 明确提示迁移到生命周期插件。
43 changes: 43 additions & 0 deletions docs/lean-harness.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,46 @@ use compatibility mode. Native provider clients retain SDK retry behavior;
custom endpoints disable retries. The loop never retries tools or interrupted
streams. `temperature=None` leaves provider defaults unchanged.
Run live tests with `MINIAGENT_TEST_MODEL` and `python -m pytest -m live -v`.

## Sessions

Pass `Session(path)` to Harness. JSONL events have version/sequence fields;
unsupported versions and corrupt complete lines fail explicitly. An incomplete
last line is discarded under an OS writer lock. Original messages and effects
remain on disk; protect Session files as sensitive user data.

Interrupted started tools are uncertain: inspect their actual effects, then use
`session.open(); session.resolve(call_id, verified_result); session.close()`.
The runtime refuses new turns until uncertainty is resolved, and never replays
tools during restore. Calls not yet started get an interrupted result.

`MINIAGENT_CONTEXT_BUDGET` includes schemas and output reserve. UTF-8 bytes are
used as a conservative token estimate, not an exact provider tokenizer.
Compaction retains whole recent turns, summarizes old data with no tools, and
falls back to an explicit omission notice. An oversized current turn errors
instead of splitting a tool group. Long-term Memory remains legacy-only.

## Skills and MCP migration

`app.apply_skill(get_skill("reviewer"))` limits schema visibility AND execution.
Switching skills or `app.apply_skill()` restores the tool catalog.
`read_skill(path)` supports scalar name/description and allowed-tools
(space-separated names or a JSON list) plus Markdown body. This is a limited
frontmatter format, not full YAML or automatic discovery.

Install `miniagent[mcp]` (validated MCP SDK 2.3.0), then:

```python
from miniagent.extensions.mcp_plugin import mcp_plugin
app.use(mcp_plugin("local", command, args, cwd=workspace))
```

Use an explicit executable and argument list, not a shell command string.
Tools are namespaced as local__tool. All calls require policy approval even
if the server declares read-only annotations. The connection has a dedicated
owner task to close its context in the same task that entered it.
Discovery failure rolls back tools/services; unload closes the process.
Remote names are closure-bound: a payload field such as `_name` is forwarded as
data and cannot change the approved tool route or bypass the Skill whitelist.
Old MCPClient and load_mcp_tools APIs fail with an actionable migration message.
Streamable HTTP is deferred.
22 changes: 15 additions & 7 deletions miniagent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,8 +264,11 @@ def load_skill(self, skill_name: str) -> bool:
if skill.temperature is not None:
self.temperature = skill.temperature
# Filter tools to skill whitelist
catalog = getattr(self, "_skill_catalog", self.tools)
self._skill_catalog = list(catalog)
self.tools = list(catalog)
if skill.tools is not None:
self.tools = [t for t in self.tools if t["name"] in skill.tools]
self.tools = [t for t in catalog if t["name"] in skill.tools]
logger.info(f"Skill '{skill_name}' filtered tools to: {[t['name'] for t in self.tools]}")

logger.info(f"Loaded skill: {skill_name}")
Expand Down Expand Up @@ -856,14 +859,16 @@ async def agent_loop(app, query, *, max_steps=10, stream=None):
if backend is None:
raise ValueError("An LLM backend is required")
if not app.messages:
app.messages.append({"role": "system", "content": app.system_prompt})
app.messages.append({"role": "user", "content": query})
app.record({"role": "system", "content": app.system_prompt})
app.record({"role": "user", "content": query})
for step in range(max_steps):
await app.emit("agent.step", step=step)
await app.emit("llm.request", step=step)
message = await backend.complete(app.messages, app.registry.schemas(), stream)
from .session import context_view
view = await context_view(app, backend)
message = await backend.complete(view, app.registry.schemas(), stream)
await app.emit("llm.response", usage=getattr(backend, "usage", {}))
app.messages.append(message)
app.record(message)
calls = message.get("tool_calls") or []
if not calls:
return message.get("content") or ""
Expand All @@ -874,12 +879,15 @@ async def agent_loop(app, query, *, max_steps=10, stream=None):
args = json.loads(call["function"]["arguments"])
if not isinstance(args, dict):
raise ValueError("Tool arguments must be an object")
result = await app.registry.execute(name, args, app.policy)
def started():
if app.session:
app.session.append("tool_started", call_id=call["id"])
result = await app.registry.execute(name, args, app.policy, started)
content = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False, default=str)
error = False
except Exception as exc:
content, error = f"Tool failed: {type(exc).__name__}: {exc}", True
content = smart_truncate(content, int(os.environ.get("TOOL_RESULT_LIMIT", "16000")))
app.messages.append({"role": "tool", "tool_call_id": call["id"], "content": content})
app.record({"role": "tool", "tool_call_id": call["id"], "content": content}, tool=True)
await app.emit("tool.end", name=name, call_id=call["id"], error=error)
raise RuntimeError("Agent reached max_steps before a final answer")
2 changes: 2 additions & 0 deletions miniagent/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ class AgentConfig:
bash_max_output: int = 50000 # BASH_MAX_OUTPUT: bash output truncation limit
tool_result_limit: int = 16000 # TOOL_RESULT_LIMIT: tool result truncation limit
max_context_messages: int = 20 # MAX_CONTEXT_MESSAGES: auto-compress conversation after N messages
context_budget: int = 32768 # MINIAGENT_CONTEXT_BUDGET: conservative token budget
confirm_dangerous: bool = True # CONFIRM_DANGEROUS: require confirmation for dangerous commands

def load_config(config_path: Optional[str] = None) -> AgentConfig:
Expand Down Expand Up @@ -122,6 +123,7 @@ def _safe_int(key: str, default: int) -> int:
config.bash_max_output = _safe_int("BASH_MAX_OUTPUT", config.bash_max_output)
config.tool_result_limit = _safe_int("TOOL_RESULT_LIMIT", config.tool_result_limit)
config.max_context_messages = _safe_int("MAX_CONTEXT_MESSAGES", config.max_context_messages)
config.context_budget = _safe_int("MINIAGENT_CONTEXT_BUDGET", config.context_budget)
if os.environ.get("CONFIRM_DANGEROUS") is not None:
config.confirm_dangerous = os.environ["CONFIRM_DANGEROUS"].lower() not in ("0", "false", "no")
if os.environ.get("ENABLE_REFLECTION") is not None:
Expand Down
228 changes: 7 additions & 221 deletions miniagent/extensions/mcp_client.py
Original file line number Diff line number Diff line change
@@ -1,226 +1,12 @@
"""Lightweight MCP (Model Context Protocol) client for MiniAgent.
"""Migration guard for the former handwritten MCP transport."""
from .mcp_plugin import mcp_plugin

Connects to MCP-compatible tool servers via stdio or SSE transport,
discovers their tools, and registers them as regular MiniAgent tools.

Usage:
from miniagent.mcp_client import load_mcp_tools

tools = load_mcp_tools("npx @anthropic/mcp-server-filesystem /tmp")
for tool in tools:
agent.add_tool(tool)
"""

from __future__ import annotations

import json
import subprocess
import threading
import uuid
from typing import Any, Callable, Dict, List, Optional

from ..logger import get_logger

logger = get_logger(__name__)
def load_mcp_tools(command, env=None):
"""Old implicit process ownership cannot be safely retained."""
raise RuntimeError("MCP API migrated: use app.use(mcp_plugin(name, command, args, env=env)); see docs/lean-harness.md")


class MCPClient:
"""A minimal MCP client using stdio (JSON-RPC over stdin/stdout)."""

def __init__(self, command: str, env: Optional[Dict[str, str]] = None):
"""
Args:
command: Shell command to start the MCP server (e.g. "npx @anthropic/mcp-server-filesystem /tmp").
env: Optional environment variables for the server process.
"""
self.command = command
self.env = env
self._process: Optional[subprocess.Popen] = None
self._lock = threading.Lock()
self._responses: Dict[str, Any] = {}
self._reader_thread: Optional[threading.Thread] = None

def start(self) -> None:
"""Start the MCP server process."""
import os
import shlex
merged_env = {**os.environ, **(self.env or {})}
self._process = subprocess.Popen(
shlex.split(self.command),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=merged_env,
)
self._reader_thread = threading.Thread(target=self._read_loop, daemon=True)
self._reader_thread.start()

# Initialize the MCP session
self._send_request("initialize", {
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {"name": "miniagent", "version": "0.1.0"},
})
# Send initialized notification
self._send_notification("notifications/initialized", {})
logger.info(f"MCP server started: {self.command}")

def stop(self) -> None:
"""Stop the MCP server process and clean up resources."""
if self._process:
try:
self._process.terminate()
try:
self._process.wait(timeout=5)
except subprocess.TimeoutExpired:
self._process.kill()
self._process.wait()
finally:
self._process = None
if self._reader_thread and self._reader_thread.is_alive():
self._reader_thread.join(timeout=2)
logger.info("MCP server stopped")

def list_tools(self) -> List[Dict[str, Any]]:
"""Discover available tools from the MCP server."""
result = self._send_request("tools/list", {})
return result.get("tools", []) if result else []

def call_tool(self, name: str, arguments: Dict[str, Any]) -> Any:
"""Call a tool on the MCP server."""
result = self._send_request("tools/call", {
"name": name,
"arguments": arguments,
})
if not result:
return {"error": "No response from MCP server"}

# MCP returns content as a list of {type, text} objects
contents = result.get("content", [])
texts = [c.get("text", "") for c in contents if c.get("type") == "text"]
return "\n".join(texts) if texts else str(result)

def _send_request(self, method: str, params: Dict[str, Any]) -> Optional[Dict]:
"""Send a JSON-RPC request and wait for response."""
req_id = str(uuid.uuid4())[:8]
message = {
"jsonrpc": "2.0",
"id": req_id,
"method": method,
"params": params,
}
self._write(message)

# Wait for response (simple polling, max 30s)
import time
for _ in range(300):
with self._lock:
if req_id in self._responses:
resp = self._responses.pop(req_id)
if "error" in resp:
logger.error(f"MCP error: {resp['error']}")
return None
return resp.get("result")
time.sleep(0.1)

logger.error(f"MCP request timed out: {method}")
return None

def _send_notification(self, method: str, params: Dict[str, Any]) -> None:
"""Send a JSON-RPC notification (no id, no response expected)."""
message = {
"jsonrpc": "2.0",
"method": method,
"params": params,
}
self._write(message)

def _write(self, message: Dict) -> None:
"""Write a JSON-RPC message to the server's stdin."""
if not self._process or not self._process.stdin:
return
content = json.dumps(message)
# MCP uses Content-Length header framing
frame = f"Content-Length: {len(content)}\r\n\r\n{content}"
try:
self._process.stdin.write(frame)
self._process.stdin.flush()
except (BrokenPipeError, OSError):
logger.error("MCP server stdin broken")

def _read_loop(self) -> None:
"""Background thread: read JSON-RPC responses from stdout."""
if not self._process or not self._process.stdout:
return

while self._process and self._process.poll() is None:
try:
# Read Content-Length header
header_line = self._process.stdout.readline()
if not header_line:
break
header_line = header_line.strip()
if not header_line.startswith("Content-Length:"):
continue
content_length = int(header_line.split(":")[1].strip())

# Read blank line separator
self._process.stdout.readline()

# Read content
content = self._process.stdout.read(content_length)
if not content:
break

msg = json.loads(content)
msg_id = msg.get("id")
if msg_id:
with self._lock:
self._responses[msg_id] = msg
except Exception:
logger.debug("MCP read error", exc_info=True)
break


def load_mcp_tools(command: str, env: Optional[Dict[str, str]] = None) -> List[Dict[str, Any]]:
"""
Start an MCP server and convert its tools into MiniAgent tool dicts.

Args:
command: Shell command to start the MCP server.
env: Optional environment variables.

Returns:
List of tool dicts compatible with agent.add_tool().
"""
client = MCPClient(command, env)
try:
client.start()
except Exception as e:
logger.error(f"Failed to start MCP server: {e}")
return []

mcp_tools = client.list_tools()
agent_tools = []

for t in mcp_tools:
tool_name = t["name"]
# Create a closure that captures the client and tool name
def _make_executor(c: MCPClient, n: str) -> Callable:
def executor(**kwargs: Any) -> Any:
return c.call_tool(n, kwargs)
executor.__name__ = n
executor.__doc__ = t.get("description", n)
return executor

agent_tools.append({
"name": tool_name,
"description": t.get("description", tool_name),
"parameters": t.get("inputSchema", {"type": "object", "properties": {}}),
"executor": _make_executor(client, tool_name),
"_mcp_client": client, # keep reference so GC doesn't kill the process
})

logger.info(f"Loaded {len(agent_tools)} tools from MCP server: {command}")
return agent_tools
def __init__(self, *args, **kwargs):
raise RuntimeError("Use the official SDK through mcp_plugin; see docs/lean-harness.md")
Loading
Loading