@unionschool/easy-agents 0.3.0 → 0.3.1

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.
@@ -20,8 +20,10 @@ class GitError(Exception):
20
20
  super().__init__(message)
21
21
 
22
22
 
23
- def git(cwd: Path, *args: str, cancel=None, timeout=60, allowed=(0,)) -> str:
23
+ def git(cwd: Path, *args: str, cancel=None, timeout=60, allowed=(0,), diagnose_push=False) -> str:
24
24
  env = {**os.environ, "GIT_TERMINAL_PROMPT": "0", "GCM_INTERACTIVE": "never"}
25
+ if diagnose_push:
26
+ env["LC_ALL"] = "C"
25
27
  env.setdefault("GIT_SSH_COMMAND", "ssh -o BatchMode=yes")
26
28
  try:
27
29
  process = subprocess.Popen(["git", "-C", str(cwd), *args], stdout=subprocess.PIPE,
@@ -34,12 +36,26 @@ def git(cwd: Path, *args: str, cancel=None, timeout=60, allowed=(0,)) -> str:
34
36
  if cancel is not None and cancel.is_set():
35
37
  raise GitError("cancelled", "已取消")
36
38
  try:
37
- stdout, _ = process.communicate(timeout=min(0.2, max(0.01, deadline - time.monotonic())))
39
+ stdout, stderr = process.communicate(timeout=min(0.2, max(0.01, deadline - time.monotonic())))
38
40
  break
39
41
  except subprocess.TimeoutExpired:
40
42
  if time.monotonic() >= deadline:
41
43
  raise GitError("git_timeout", "Git 操作超时") from None
42
44
  if process.returncode not in allowed:
45
+ if diagnose_push:
46
+ detail = (stdout + stderr).lower()
47
+ for pattern, code, reason in (
48
+ ('[rejected] (fetch first)', 'git_push_race', '远程分支已推进'),
49
+ ('[rejected] (non-fast-forward)', 'git_push_race', '远程分支已推进'),
50
+ ('host key verification failed', 'git_push', 'SSH 主机密钥未受信任'),
51
+ ('protected branch', 'git_push', '远程分支受保护'),
52
+ ('permission denied', 'git_push', '远程权限不足'),
53
+ ('authentication failed', 'git_push', '远程身份验证失败'),
54
+ ('could not read username', 'git_push', '缺少远程凭据'),
55
+ ('remote rejected', 'git_push', '远程拒绝了推送'),
56
+ ):
57
+ if pattern in detail:
58
+ raise GitError(code, reason + ',请核对后重发 /sync')
43
59
  # Git 错误可能包含带凭据的远程地址,不向平台回传原文。
44
60
  raise GitError("git_failed", "Git 操作失败,请检查远程权限、网络及分支状态")
45
61
  return stdout.strip()
@@ -0,0 +1,165 @@
1
+ """供四种工具通过命令行调用平台 MCP,凭据仅从受限文件读取。"""
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+
9
+ import httpx
10
+
11
+ from .file_delivery import manifest
12
+ from .git_sync import GitError, git, repository_root
13
+
14
+
15
+ class MCPError(Exception):
16
+ pass
17
+
18
+
19
+ def request(credentials: dict, method: str, params: dict, client=None):
20
+ headers = {"Authorization": "Bearer " + credentials["agent_token"],
21
+ "Accept": "application/json, text/event-stream"}
22
+ if run_id := os.environ.get("EASYAGENTS_RUN_ID"):
23
+ headers["X-EasyAgents-Run-Id"] = run_id
24
+ owned = client is None
25
+ client = client or httpx.Client(timeout=30, follow_redirects=False)
26
+ try:
27
+ def send(name, arguments, request_id):
28
+ body = {"jsonrpc": "2.0", "method": name, "params": arguments}
29
+ if request_id is not None:
30
+ body["id"] = request_id
31
+ response = client.post(credentials["server"] + "/mcp", headers=headers, json=body)
32
+ if response.status_code >= 400:
33
+ raise MCPError(f"MCP HTTP {response.status_code},请检查 Agent 凭据或平台状态")
34
+ if request_id is None:
35
+ return None
36
+ data = response.json()
37
+ if data.get("error"):
38
+ raise MCPError("MCP 协议请求失败")
39
+ if "result" not in data:
40
+ raise MCPError("MCP 缺少结果")
41
+ if response.headers.get("Mcp-Session-Id"):
42
+ headers["Mcp-Session-Id"] = response.headers["Mcp-Session-Id"]
43
+ return data["result"]
44
+
45
+ initialized = send("initialize", {"protocolVersion": "2025-03-26", "capabilities": {},
46
+ "clientInfo": {"name": "easyagents-client", "version": "1"}}, 1)
47
+ headers["MCP-Protocol-Version"] = initialized["protocolVersion"]
48
+ send("notifications/initialized", {}, None)
49
+ return send(method, params, 2)
50
+ except (httpx.HTTPError, ValueError, KeyError, TypeError):
51
+ raise MCPError("MCP 请求或响应无效,请检查网络及平台状态") from None
52
+ finally:
53
+ if owned:
54
+ client.close()
55
+
56
+
57
+ def branch_remote(cwd, branch, commit):
58
+ if (not isinstance(branch, str) or branch == 'HEAD' or branch.startswith(('-', 'refs/'))
59
+ or not isinstance(commit, str) or not re.fullmatch(r'(?:[0-9a-f]{40}|[0-9a-f]{64})', commit)):
60
+ raise MCPError('须提供任务分支和完整提交 SHA')
61
+ git(cwd, 'check-ref-format', 'refs/heads/' + branch)
62
+ remotes = git(cwd, 'remote').splitlines()
63
+ remote = 'github' if 'github' in remotes else remotes[0] if len(remotes) == 1 else None
64
+ if remote is None:
65
+ raise MCPError('无法确定任务仓库远程,请检查 Git 配置')
66
+ return remote, f'refs/heads/{branch}'
67
+
68
+
69
+ def require_pushed_commit(branch, commit):
70
+ cwd = Path.cwd()
71
+ remote, ref = branch_remote(cwd, branch, commit)
72
+ if git(cwd, 'ls-remote', '--heads', remote, ref).split() != [commit, ref]:
73
+ raise MCPError('任务分支远端尚未指向本轮提交,请先推送后重试')
74
+ return remote
75
+
76
+
77
+ def require_current_delivery(branch, commit):
78
+ cwd = Path.cwd()
79
+ remote = require_pushed_commit(branch, commit)
80
+ head = git(cwd, 'ls-remote', remote, 'HEAD').split()
81
+ if len(head) != 2 or head[1] != 'HEAD':
82
+ raise MCPError('无法确定远端主分支,请核对远端默认分支后再提交')
83
+ latest = head[0]
84
+ # 按查询到的提交取对象,避免读到其他操作写入的 FETCH_HEAD。
85
+ try:
86
+ git(cwd, 'fetch', '--no-tags', '--no-prune', '--no-recurse-submodules',
87
+ '--no-write-fetch-head', '--refmap=', remote, latest)
88
+ except GitError as exc:
89
+ raise MCPError(f'无法拉取远端主分支提交 {latest}。{exc.message}') from None
90
+ if git(cwd, 'merge-base', latest, commit, allowed=(0, 1)) != latest:
91
+ raise MCPError(f'本轮交付尚未包含远端主分支提交 {latest},请合入后重跑测试、推送并重新提交')
92
+
93
+
94
+ def publish_branch(branch, commit, document):
95
+ cwd = Path.cwd()
96
+ remote, ref = branch_remote(cwd, branch, commit)
97
+ if not isinstance(document, str) or not document:
98
+ raise MCPError('须提供任务单路径')
99
+ tip = git(cwd, 'ls-remote', '--heads', remote, ref).split()
100
+ if tip:
101
+ git(cwd, 'fetch', '--no-tags', '--no-write-fetch-head', remote, ref)
102
+ target = tip[0]
103
+ else:
104
+ target = git(cwd, 'rev-parse', 'HEAD')
105
+ if git(cwd, 'merge-base', commit, target, allowed=(0, 1)) != commit:
106
+ raise MCPError('任务单提交不在任务分支的历史中')
107
+ if git(cwd, 'cat-file', '-t', f'{commit}:{document}', allowed=(0, 128)) != 'blob':
108
+ raise MCPError('任务单提交中找不到指定文档')
109
+ if not tip:
110
+ # 空 lease 只允许创建新引用,远端被抢先建立时不能覆盖。
111
+ git(cwd, 'push', f'--force-with-lease={ref}:', remote, f'{target}:{ref}')
112
+ require_pushed_commit(branch, target)
113
+
114
+
115
+ def main(argv=None):
116
+ parser = argparse.ArgumentParser(description="调用 EasyAgents MCP;list 返回工具签名")
117
+ parser.add_argument("--credential", type=Path)
118
+ parser.add_argument("tool")
119
+ parser.add_argument("arguments", nargs="?", default="{}")
120
+ args = parser.parse_args(argv)
121
+ if not args.credential:
122
+ parser.error("必须提供 --credential")
123
+ try:
124
+ credentials = json.loads(args.credential.read_text())
125
+ arguments = json.loads(args.arguments)
126
+ if not isinstance(arguments, dict):
127
+ raise MCPError("工具参数须为 JSON 对象")
128
+ paths = arguments.pop('file_paths', None)
129
+ if args.tool == 'publish_task':
130
+ if 'file_manifest' in arguments or paths is not None:
131
+ raise MCPError('新任务登记请使用任务分支,登记时不接受文件清单')
132
+ if arguments.get('dispatch_mode', 'platform') == 'platform':
133
+ if not arguments.get('task_branch'):
134
+ raise MCPError('平台派发必须填写任务分支')
135
+ publish_branch(arguments['task_branch'], arguments.get('document_commit_sha'),
136
+ arguments.get('document_path'))
137
+ if paths is not None:
138
+ if args.tool not in ('submit_task', 'review_task', 'reassign_task') or 'file_manifest' in arguments:
139
+ raise MCPError('文件清单参数不适用于本次操作')
140
+ try:
141
+ root = repository_root(Path.cwd())
142
+ except GitError:
143
+ root = Path.cwd()
144
+ arguments['file_manifest'] = manifest(root, paths)
145
+ if args.tool == 'submit_task' and arguments.get('delivery_commit_sha'):
146
+ require_current_delivery(arguments.get('branch'), arguments['delivery_commit_sha'])
147
+ method, params = ("tools/list", {}) if args.tool == "list" else (
148
+ "tools/call", {"name": args.tool, "arguments": arguments})
149
+ result = request(credentials, method, params)
150
+ print(json.dumps(result, ensure_ascii=False))
151
+ if result.get("isError"):
152
+ raise SystemExit(1)
153
+ except (OSError, ValueError, KeyError, TypeError):
154
+ print("MCP 凭据文件或参数无效")
155
+ raise SystemExit(1) from None
156
+ except MCPError as exc:
157
+ print(str(exc))
158
+ raise SystemExit(1) from None
159
+ except GitError as exc:
160
+ print(exc.message)
161
+ raise SystemExit(1) from None
162
+
163
+
164
+ if __name__ == "__main__":
165
+ main()