voyoagent 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.
voyoagent/__init__.py ADDED
@@ -0,0 +1,72 @@
1
+ __version__ = "0.1.0"
2
+
3
+ from voyoagent.agent import Voyo_Agent
4
+ from voyoagent.yo_agent import Yo_Agent, BUILTIN_TOOLS
5
+ from voyoagent.prompt import AgentPrompt
6
+ from voyoagent.agent_hook import Agent_Hook
7
+ from voyoagent.agent_base import (
8
+ AgentEvent,
9
+ AgentEventType,
10
+ RunStartEvent,
11
+ ThinkingStartEvent,
12
+ ThinkingDeltaEvent,
13
+ ThinkingEndEvent,
14
+ TextStartEvent,
15
+ TextDeltaEvent,
16
+ ToolCallEvent,
17
+ ToolResultEvent,
18
+ ToolErrorEvent,
19
+ ResponseCompletedEvent,
20
+ TurnEndEvent,
21
+ DoneEvent,
22
+ ErrorEvent,
23
+ )
24
+ from voyoagent.tools import (
25
+ AgentTool,
26
+ LOAD_SKILL_TOOL,
27
+ WEATHER_TOOL_ENTRY,
28
+ READ_FILE_ENTRY,
29
+ WRITE_FILE_ENTRY,
30
+ REPLACE_FILE_ENTRY,
31
+ LIST_DIR_ENTRY,
32
+ RUN_SHELL_ENTRY,
33
+ )
34
+ from voyoagent.tools.tool_types import ToolDef, ToolHandler, ToolEntry
35
+ from voyoagent.utils.exception import YoAgentCode, YoAgentException
36
+
37
+ __all__ = [
38
+ "__version__",
39
+ "Voyo_Agent",
40
+ "Yo_Agent",
41
+ "BUILTIN_TOOLS",
42
+ "AgentPrompt",
43
+ "Agent_Hook",
44
+ "AgentEvent",
45
+ "AgentEventType",
46
+ "RunStartEvent",
47
+ "ThinkingStartEvent",
48
+ "ThinkingDeltaEvent",
49
+ "ThinkingEndEvent",
50
+ "TextStartEvent",
51
+ "TextDeltaEvent",
52
+ "ToolCallEvent",
53
+ "ToolResultEvent",
54
+ "ToolErrorEvent",
55
+ "ResponseCompletedEvent",
56
+ "TurnEndEvent",
57
+ "DoneEvent",
58
+ "ErrorEvent",
59
+ "AgentTool",
60
+ "LOAD_SKILL_TOOL",
61
+ "WEATHER_TOOL_ENTRY",
62
+ "READ_FILE_ENTRY",
63
+ "WRITE_FILE_ENTRY",
64
+ "REPLACE_FILE_ENTRY",
65
+ "LIST_DIR_ENTRY",
66
+ "RUN_SHELL_ENTRY",
67
+ "ToolDef",
68
+ "ToolHandler",
69
+ "ToolEntry",
70
+ "YoAgentCode",
71
+ "YoAgentException",
72
+ ]
voyoagent/agent.py ADDED
@@ -0,0 +1,89 @@
1
+ from voyo.model import OpenAiResponsesClient,ModelUsage,ThinkingEffort
2
+ from voyo.model.types import OpenAiResponsesMsg,ResponsesFunctionCallOutputItem,ResponsesFunctionCallItem
3
+
4
+
5
+ from voyo.utils.json import JSON
6
+ from typing import TypedDict,Literal,AsyncIterator
7
+ import sys
8
+ from voyoagent.constants import Constants
9
+
10
+ from voyoagent.agent_base import AgentEvent,RunStartEvent,TurnEndEvent,DoneEvent
11
+ from voyoagent.agent_chat import AgentChat
12
+ from voyoagent.agent_hook import Agent_Hook
13
+ from voyoagent.functional.logger_event_handler import logger_event_handler
14
+ from voyoagent.prompt import AgentPrompt
15
+ from voyoagent.constants import root_dir
16
+ from voyoagent.agent_mcp import Agent_MCP
17
+ from voyoagent.agent_skill import Agent_Skill
18
+
19
+
20
+ class Voyo_Agent(AgentChat, Agent_MCP, Agent_Skill):
21
+ history: list[OpenAiResponsesMsg]
22
+ model:str
23
+ effort: ThinkingEffort
24
+ next_call_tools:list[ResponsesFunctionCallOutputItem|ResponsesFunctionCallItem]
25
+ agent_prompt: AgentPrompt
26
+
27
+ def __init__(
28
+ self,
29
+ model:str=None,
30
+ base_url:str="",
31
+ api_key:str="",
32
+ effort:ThinkingEffort="none",
33
+ system_prompt_path:str="",
34
+ soul_prompt_path:str="",
35
+ skill_dirs:list[str]|None=None
36
+ ):
37
+ self.client= OpenAiResponsesClient(
38
+ base_url=base_url,
39
+ api_key=api_key
40
+ )
41
+
42
+ system_prompt_path=system_prompt_path if system_prompt_path else str(root_dir / "prompts" / "system.md")
43
+ soul_prompt_path=soul_prompt_path if soul_prompt_path else str(root_dir / "prompts" / "soul.md")
44
+
45
+ super().__init__(AgentEvent())
46
+ self.model=model
47
+ self.effort=effort
48
+ self.history=[]
49
+ self.next_call_tools=[]
50
+ self.skill_dirs=skill_dirs if skill_dirs else []
51
+ self.agent_prompt = AgentPrompt(
52
+ system_prompt_path=system_prompt_path,
53
+ soul_prompt_path=soul_prompt_path
54
+ )
55
+
56
+ logger_event_handler(self.agent_event)
57
+
58
+ async def init(self):
59
+ #先触发钩子,订阅方注入的 fragment 能进入随后的统一提示词
60
+ self.registry_mcp_base_tools()
61
+ if self.skill_dirs:
62
+ await self.registry_skill(self.skill_dirs)
63
+ await self.agent_hook.emit_agent_init()
64
+
65
+
66
+ async def run(self,content:str):
67
+ await self.agent_hook.emit_user_input(content)
68
+ self.agent_event.write(RunStartEvent())
69
+ await self.achat(content)
70
+ for _ in range(Constants.MAX_TURNS):
71
+ if not self.next_call_tools: break
72
+ self.history.extend(self.next_call_tools)
73
+ self.next_call_tools=[]
74
+ await self.achat()
75
+ self.agent_event.write(TurnEndEvent())
76
+ await self.agent_hook.emit_dialog_end()
77
+ self.agent_event.write(DoneEvent(self._final_text()))
78
+
79
+ def _final_text(self)->str:
80
+ #最终回答取最后一条 assistant 文本消息
81
+ for msg in reversed(self.history):
82
+ if msg.get("role")=="assistant" and isinstance(msg.get("content"),str):
83
+ return msg["content"]
84
+ return ""
85
+
86
+
87
+
88
+
89
+
@@ -0,0 +1,94 @@
1
+
2
+ from typing import Literal,Callable
3
+ from voyoagent.utils.subject import Subject
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass
9
+ class RunStartEvent:
10
+ type: Literal["run_start"]="run_start"
11
+
12
+ @dataclass
13
+ class ThinkingStartEvent:
14
+ type: Literal["thinking_start"]="thinking_start" #思考流开始
15
+
16
+ @dataclass
17
+ class ThinkingDeltaEvent:
18
+ content: str #流式思考增量
19
+ type: Literal["thinking_delta"]="thinking_delta"
20
+
21
+ @dataclass
22
+ class ThinkingEndEvent:
23
+ type: Literal["thinking_end"]="thinking_end" #思考流结束
24
+
25
+ @dataclass
26
+ class TextStartEvent:
27
+ type: Literal["text_start"]="text_start" #正文流开始
28
+
29
+ @dataclass
30
+ class TextDeltaEvent:
31
+ content: str #流式回答增量
32
+ type: Literal["text_delta"]="text_delta"
33
+
34
+ @dataclass
35
+ class ToolCallEvent:
36
+ call_id: str
37
+ name: str
38
+ arguments: str #原始 JSON 字符串
39
+ type: Literal["tool_call"]="tool_call"
40
+
41
+ @dataclass
42
+ class ToolResultEvent:
43
+ call_id: str
44
+ name:str
45
+ result: str
46
+ type: Literal["tool_result"]="tool_result"
47
+
48
+ @dataclass
49
+ class ToolErrorEvent:
50
+ call_id: str
51
+ name: str
52
+ error: str #错误信息,同时作为 function_call_output 回传给模型
53
+ type: Literal["tool_error"]="tool_error"
54
+
55
+ @dataclass
56
+ class ResponseCompletedEvent:
57
+ type: Literal["response_completed"]="response_completed" #本轮模型响应流结束
58
+
59
+ @dataclass
60
+ class TurnEndEvent:
61
+ type: Literal["turn_end"]="turn_end" #一轮 function_call 回传完成
62
+
63
+ @dataclass
64
+ class DoneEvent:
65
+ content: str #最终全文
66
+ type: Literal["done"]="done"
67
+
68
+ @dataclass
69
+ class ErrorEvent:
70
+ content: str #错误信息
71
+ type: Literal["error"]="error"
72
+
73
+
74
+ type AgentEventType = (
75
+ RunStartEvent | ThinkingStartEvent | ThinkingDeltaEvent | ThinkingEndEvent
76
+ | TextStartEvent | TextDeltaEvent | ResponseCompletedEvent
77
+ | ToolCallEvent | ToolResultEvent | ToolErrorEvent
78
+ | TurnEndEvent | DoneEvent | ErrorEvent
79
+ )
80
+
81
+
82
+ class AgentEvent():
83
+ subject:Subject[AgentEventType]
84
+
85
+
86
+
87
+ def __init__(self):
88
+ self.subject=Subject[AgentEventType]()
89
+
90
+ def write(self,event:AgentEventType):
91
+ self.subject.next(event)
92
+
93
+ def subscribe(self,sub:Callable[[AgentEventType],None])->Callable[[],None]:
94
+ return self.subject.subscribe(sub)
@@ -0,0 +1,88 @@
1
+ from voyoagent.tools.tool import AgentTool
2
+ from voyoagent.agent_base import AgentEvent,ThinkingDeltaEvent,ThinkingEndEvent,ThinkingStartEvent,ResponseCompletedEvent,TextDeltaEvent,TextStartEvent
3
+
4
+ from typing import AsyncIterator
5
+ from voyo.model.types import OpenAiResponsesMsg,ResponsesFunctionCallOutputItem,ResponsesFunctionCallItem
6
+ from voyo.model import OpenAiResponsesClient,ModelUsage
7
+ from voyoagent.agent_hook import Agent_Hook
8
+ from voyoagent.prompt import AgentPrompt
9
+
10
+
11
+ class AgentChat(AgentTool):
12
+ client: OpenAiResponsesClient
13
+ history: list[OpenAiResponsesMsg]
14
+ agent_hook: Agent_Hook
15
+ agent_prompt: AgentPrompt
16
+
17
+ def __init__(self,agent_event:AgentEvent):
18
+ self.history=[]
19
+ self.agent_hook=Agent_Hook()
20
+ super().__init__(agent_event)
21
+
22
+ async def achat(self,content:str=None)->AsyncIterator[str]|None:
23
+ if content:
24
+ msg:OpenAiResponsesMsg={"role": "user", "content": content}
25
+ self.history.append(msg)
26
+
27
+ usage:ModelUsage=ModelUsage()
28
+
29
+ r=await self.client.achat(
30
+ model=self.model,
31
+ effort=self.effort,
32
+ stream=True,
33
+ messages= self.agent_prompt.get_unified_message() + self.history,
34
+ usage=usage,
35
+ extra_body={
36
+ "tools": self.wire_tools or [],
37
+ }
38
+ )
39
+
40
+ thinking_result=""
41
+ text_result= ""
42
+ thinking=False
43
+ async for i in r:
44
+ event=OpenAiResponsesClient._parse_event(i)
45
+ if not event:
46
+ continue
47
+
48
+ etype= event.get("type","")
49
+
50
+ text= event.get("delta") if etype == "response.output_text.delta" else ""
51
+ thinking_text= event.get("delta") if etype in ("response.reasoning_text.delta", "response.reasoning_summary_text.delta") else ""
52
+
53
+ event= OpenAiResponsesClient._parse_event(i)
54
+
55
+ if thinking_text:
56
+ if not thinking:
57
+ thinking=True
58
+ self.agent_event.write(ThinkingStartEvent())
59
+ self.agent_event.write(ThinkingDeltaEvent(thinking_text))
60
+ thinking_result+=thinking_text
61
+
62
+ if text:
63
+ if thinking:
64
+ self.agent_event.write(ThinkingEndEvent())
65
+ thinking=False
66
+ if not text_result:
67
+ self.agent_event.write(TextStartEvent())
68
+ self.agent_event.write(TextDeltaEvent(text))
69
+ text_result+=text
70
+
71
+ self.next_call_tools= await self.check_and_call_tool(event)
72
+
73
+ self.agent_event.write(ResponseCompletedEvent())
74
+ if thinking_result:
75
+ self.history.append({
76
+ "type": "reasoning",
77
+ "content": [{
78
+ "type": "reasoning_text",
79
+ "text": thinking_result
80
+ }]
81
+ })
82
+
83
+ if text_result:
84
+ self.history.append(
85
+ {"role": "assistant", "content": text_result}
86
+ )
87
+
88
+ return None
@@ -0,0 +1,16 @@
1
+ from voyo.utils.token import estimate_token_count
2
+
3
+
4
+ class Agent_Context():
5
+ context_tokens: int
6
+
7
+ usage_input_tokens: int
8
+ usage_output_tokens: int
9
+ usage_cache_input_tokens: int
10
+
11
+ def __init__(self):
12
+ self.context_tokens=0
13
+ self.usage_input_tokens=0
14
+ self.usage_output_tokens=0
15
+ self.usage_cache_input_tokens=0
16
+
@@ -0,0 +1,27 @@
1
+ import inspect
2
+ from typing import Callable, Optional, Awaitable
3
+
4
+ from voyoagent.utils.subject import ASubject
5
+
6
+ #钩子回调,支持同步函数或 async 函数
7
+ Handler=Callable[..., Optional[Awaitable[None]]]
8
+
9
+
10
+ class Agent_Hook():
11
+ #agent 生命周期钩子,注册到 Voyo_Agent 后由其在对应节点触发
12
+ on_agent_init:ASubject[None] #agent 初始化完成
13
+ on_user_input:ASubject[str] #每次用户发起对话,参数: content
14
+ on_dialog_end:ASubject[None] #每次对话结束
15
+
16
+ def __init__(self):
17
+ self.on_agent_init=ASubject[None]()
18
+ self.on_user_input=ASubject[str]()
19
+ self.on_dialog_end=ASubject[None]()
20
+
21
+
22
+ async def emit_agent_init(self):
23
+ await self.on_agent_init.next(None)
24
+ async def emit_user_input(self,content:str):
25
+ await self.on_user_input.next(content)
26
+ async def emit_dialog_end(self):
27
+ await self.on_dialog_end.next(None)
voyoagent/agent_mcp.py ADDED
@@ -0,0 +1,301 @@
1
+ import asyncio
2
+ import logging
3
+ import traceback
4
+ from contextlib import AsyncExitStack
5
+ from dataclasses import dataclass, field
6
+ from typing import TypedDict, Literal
7
+ from voyo.utils.json import JSON
8
+ from mcp import ClientSession, StdioServerParameters
9
+ from mcp.client.stdio import stdio_client
10
+ from mcp.client.streamable_http import streamable_http_client
11
+ from voyoagent.utils.exception import YoAgentCode,YoAgentException
12
+
13
+ logger= logging.getLogger(__name__)
14
+
15
+ class Agent_MCP_Interface:
16
+ #Agent_MCP 的对外接口,宿主 agent 只依赖这一层。
17
+ #状态机:registry_mcp 后 loading(连接/安装中) -> ready(可用) | error(失败,可 reload 重试)。
18
+
19
+
20
+ def registry_tool(self, tool_entry):
21
+ #宿主 agent 提供的注册入口:接收 (schema, handler) 二元组,写入 agent 工具表。
22
+ #多继承时由 MRO 中更靠前的子类覆盖此声明。
23
+ raise NotImplementedError
24
+
25
+
26
+ def unregistry_tool(self, tool_name: str):
27
+ #宿主 agent 提供的注销入口:按 schema name 从 agent 工具表移除条目。
28
+ #server 断开/重载时必须,否则工具表残留死 handler,重注册还会撞「重复注册」。
29
+ raise NotImplementedError
30
+
31
+
32
+ async def registry_mcp(self, name: str, command: str = "", args: list[str] | None = None, url: str = ""):
33
+ #连接一个标准 MCP server,并把它的全部工具注册进 agent(工具名加前缀 mcp__<server>__<原名>)。
34
+ #command=stdio 子进程接入(如 npx 安装耗时,状态停在 loading);url=streamable http 接入,二者必传其一。
35
+ #连接在后台进行、立即返回;失败只落 error 状态。同名 server 已存在且非 error 状态时抛 ValueError。
36
+ raise NotImplementedError
37
+
38
+
39
+ async def reload_mcp(self, name: str):
40
+ #按注册时的原参数重连指定 server:ready 用于刷新工具列表,error 用于重试;loading 中拒绝。
41
+ raise NotImplementedError
42
+
43
+
44
+ async def remove_mcp(self, name: str):
45
+ #断开指定 server,注销它提供的全部工具并删除状态记录;loading 中拒绝。
46
+ raise NotImplementedError
47
+
48
+
49
+ def list_mcp(self) -> list[dict]:
50
+ #返回全部 server 的状态快照(同步、立即返回):
51
+ #每项含 name/state(loading|ready|error)/error/tools/command/args/url。
52
+ raise NotImplementedError
53
+
54
+
55
+ def registry_mcp_base_tools(self):
56
+ #把 mcp_list / mcp_remove / mcp_reload 三个管理动作注册为 agent 工具,
57
+ #让模型自主查看、重载、移除 MCP server。是否调用由宿主决定(不调则模型无此能力)。
58
+ raise NotImplementedError
59
+
60
+
61
+ async def close(self):
62
+ #整体收尾:取消后台注册任务、断开全部 server 并清空状态。宿主 agent 销毁时调用一次。
63
+ raise NotImplementedError
64
+
65
+
66
+ @dataclass
67
+ class MCPServerState:
68
+ #server 连接状态快照:loading(连接/安装中) -> ready | error
69
+ name: str
70
+ state: Literal["loading", "error", "ready"] = "loading"
71
+ error: str = ""
72
+ tools: list[str] = field(default_factory=list)
73
+ command: str = ""
74
+ args: list[str] = field(default_factory=list)
75
+ url: str = ""
76
+ mcp_session: ClientSession =None
77
+ keep_event: asyncio.Event =None
78
+ task: asyncio.Task= None
79
+
80
+
81
+ class Mcp_Tool_Info(TypedDict):
82
+ tool_full_name: str
83
+ mcp_name: str
84
+ tool_name: str
85
+
86
+ MCP_LIST_TOOL = {
87
+ "type": "function",
88
+ "name": "mcp_list",
89
+ "description": "查看当前已注册的 MCP server 列表及状态(loading=连接/安装中,ready=可用,error=失败及原因),含各 server 提供的工具。",
90
+ "parameters": {"type": "object", "properties": {}},
91
+ }
92
+ MCP_REMOVE_TOOL = {
93
+ "type": "function",
94
+ "name": "mcp_remove",
95
+ "description": "断开并移除指定 MCP server,其提供的工具随之注销。",
96
+ "parameters": {
97
+ "type": "object",
98
+ "properties": {"name": {"type": "string", "description": "MCP server 名称"}},
99
+ "required": ["name"],
100
+ },
101
+ }
102
+ MCP_RELOAD_TOOL = {
103
+ "type": "function",
104
+ "name": "mcp_reload",
105
+ "description": "用原参数重新连接指定 MCP server(ready 或 error 状态均可),并以重连后的工具列表为准。",
106
+ "parameters": {
107
+ "type": "object",
108
+ "properties": {"name": {"type": "string", "description": "MCP server 名称"}},
109
+ "required": ["name"],
110
+ },
111
+ }
112
+
113
+
114
+
115
+
116
+ class Agent_MCP(Agent_MCP_Interface):
117
+
118
+ mcp_states: dict[str, MCPServerState]
119
+
120
+ #MCP server 接入器 mixin:把标准 MCP server 的工具转成 (schema, handler) 交给 registry_tool 注册
121
+ def __init__(self, *args, **kwargs):
122
+ super().__init__(*args, **kwargs)
123
+ self.mcp_states= {} #mcp_name : mcpServerState
124
+
125
+ def registry_tool(self, tool_entry):
126
+ #空实现仅声明接口;实际注册由 MRO 中更前的子类覆盖(如 Voyo_Agent 的工具注册表)
127
+ pass
128
+
129
+
130
+ def unregistry_tool(self, tool_name):
131
+ #同上,standalone 空实现;真实注销由宿主覆盖
132
+ pass
133
+
134
+
135
+ async def registry_mcp(self, name: str, command: str = "", args: list[str] | None = None, url: str = ""):
136
+ #command=stdio 子进程接入(如 npx 安装耗久则停留在 loading);url=streamable http 接入
137
+ #连接在后台进行、不阻塞调用方(如 agent 初始化),失败只落 error 状态不抛出
138
+ if not name:
139
+ raise ValueError("MCP server 名称不能为空")
140
+ old = self.mcp_states.get(name)
141
+ if old and old.state != "error":
142
+ raise ValueError(f"MCP server 已注册且未失败: {name!r} ({old.state})")
143
+ await self._register(name, command, args or [], url)
144
+
145
+
146
+ async def reload_mcp(self, name: str):
147
+ #按原参数重连;ready 可刷新工具列表,error 可重试
148
+ mcp_state = self._get_mcp_state(name)
149
+ if mcp_state.state == "loading":
150
+ raise ValueError(f"{name!r} 正在连接中,暂不能 reload")
151
+ await self._register(name, mcp_state.command, mcp_state.args, mcp_state.url)
152
+
153
+
154
+ async def _register(self, name: str, command: str, args: list[str], url: str):
155
+ if name in self.mcp_states:
156
+ await self._drop(name) #error 重试前收掉旧连接,避免子进程残留
157
+ self.mcp_states[name] = mcp_state = MCPServerState(name=name, command=command, args=args, url=url)
158
+ mcp_state.task = asyncio.create_task(self._owner(mcp_state, command, args, url))
159
+
160
+
161
+ async def _owner(self, mcp_state:MCPServerState, command: str, args: list[str], url: str):
162
+
163
+ stack = AsyncExitStack()
164
+ async with stack:
165
+ try:
166
+ mcp_state.state="loading"
167
+ if command:
168
+ params = StdioServerParameters(command=command, args=args)
169
+ read, write = await stack.enter_async_context(stdio_client(params))
170
+ elif url:
171
+ read, write = await stack.enter_async_context(streamable_http_client(url))
172
+ else:
173
+ raise ValueError("registry_mcp 需要 command(stdio) 或 url(http) 之一")
174
+
175
+ mcp_state.mcp_session = await stack.enter_async_context(ClientSession(read, write))
176
+ await mcp_state.mcp_session.initialize()
177
+ mcp_state.keep_event=keep_event=asyncio.Event()
178
+ await self._registry_owner_tools(mcp_state)
179
+ mcp_state.state="ready"
180
+ await keep_event.wait()
181
+ except Exception as e:
182
+ logger.error("MCP %s 连接失败:\n%s", mcp_state.name, traceback.format_exc())
183
+ mcp_state.error=str(e)
184
+ mcp_state.state= "error"
185
+ finally:
186
+ #正常/报错/强杀退出都摘掉已注册工具(unregistry 对不存在名字是 no-op)
187
+ for tool_name in mcp_state.tools:
188
+ self.unregistry_tool(self.get_tool_full_name(mcp_state.name, tool_name))
189
+ self.clear_mcp_state(mcp_state)
190
+
191
+ def clear_mcp_state(self,mcp_state: MCPServerState):
192
+ #仅摘运行时引用;state/error 留给 list_mcp 展示与 registry_mcp 的重试判断
193
+ mcp_state.mcp_session=None
194
+ mcp_state.keep_event=None
195
+ mcp_state.task=None
196
+
197
+ async def _registry_owner_tools(self,mcp_state: MCPServerState):
198
+ tools=(await mcp_state.mcp_session.list_tools()).tools
199
+ mcp_state.tools=[t.name for t in tools] #注销与 list_mcp 都以此为准
200
+ for tool in tools:
201
+ self._registry_tool(mcp_state.name, mcp_state.mcp_session, tool)
202
+
203
+ async def remove_mcp(self, name: str):
204
+ #断开并注销整个 server(含状态记录)
205
+ state = self._get_mcp_state(name)
206
+ if state.state == "loading":
207
+ raise ValueError(f"{name!r} 正在连接中,暂不能 remove")
208
+ await self._drop(name)
209
+ del self.mcp_states[name]
210
+
211
+
212
+ def list_mcp(self) -> list[dict]:
213
+ #各 server 状态快照
214
+
215
+ return [{
216
+ "name": name,
217
+ "state": state.state,
218
+ "command": state.command,
219
+ "args": state.args,
220
+ "url": state.url,
221
+ "error": state.error,
222
+ "tools": state.tools
223
+ } for name, state in self.mcp_states.items()]
224
+
225
+
226
+ def registry_mcp_base_tools(self):
227
+ #把 MCP 管理能力注册为 agent 工具,让 agent 自主 list/remove/reload
228
+ self.registry_tool((MCP_LIST_TOOL, self._tool_list))
229
+ self.registry_tool((MCP_REMOVE_TOOL, self._tool_remove))
230
+ self.registry_tool((MCP_RELOAD_TOOL, self._tool_reload))
231
+
232
+
233
+ async def _tool_list(self, args: dict) -> str:
234
+ return JSON.json(self.list_mcp())
235
+
236
+ async def _tool_remove(self, args: dict) -> str:
237
+ name = args.get("name", "")
238
+ await self.remove_mcp(name)
239
+ return f"已移除 MCP server: {name}"
240
+
241
+ #
242
+ # {name: str} #name mcp_name
243
+ #
244
+ async def _tool_reload(self, args: dict) -> str:
245
+ #后台重载:不让模型在 npx 安装上阻塞整个 turn,用 mcp_list 轮询结果
246
+ name = args.get("name", "")
247
+ await self.reload_mcp(name)
248
+ return f"已在后台重载 MCP server: {name},可用 mcp_list 查看状态"
249
+
250
+
251
+ def _get_mcp_state(self, name: str) -> MCPServerState:
252
+ state = self.mcp_states.get(name)
253
+ if state is None:
254
+ raise YoAgentException(YoAgentCode.MCP_ERROR, f"MCP server 未注册: {name!r},可用 mcp_list 查看现存列表")
255
+
256
+ return state
257
+
258
+ def get_tool_full_name(self,mcp_name:str, tool_name:str)->str:
259
+ return f"mcp__{mcp_name}__{tool_name}"
260
+
261
+ def _registry_tool(self, mcp_name: str, session: ClientSession, tool) -> None:
262
+ self.registry_tool(({
263
+ "type": "function",
264
+ "name": self.get_tool_full_name(mcp_name,tool.name),
265
+ "description": tool.description or "",
266
+ "parameters": tool.input_schema or {"type": "object", "properties": {}},
267
+ }, self._make_handler(session, tool.name)))
268
+
269
+
270
+ @staticmethod
271
+ def _make_handler(session: ClientSession, tool_name: str):
272
+ async def handler(args: dict) -> str:
273
+ result = await session.call_tool(tool_name, args or {})
274
+ texts = [c.text for c in result.content if getattr(c, "text", None)]
275
+ body = "\n".join(texts) if texts else "(无文本返回)"
276
+ return f"工具执行失败: {body}" if result.is_error else body
277
+ return handler
278
+
279
+
280
+ async def _drop(self, name: str):
281
+ #断开单个 server:唤醒/取消 owner 任务;工具注销与状态清理都由 owner 的 finally 完成
282
+ mcp_state= self.mcp_states.get(name)
283
+ if mcp_state is None:
284
+ return
285
+
286
+ if mcp_state.keep_event:
287
+ mcp_state.keep_event.set() #优雅唤醒 owner 正常退出
288
+ task= mcp_state.task
289
+ if task is not None and not task.done():
290
+ try:
291
+ #正常毫秒级退出;卡在安装/初始化/list_tools 时由超时取消强杀
292
+ await asyncio.wait_for(task, 5)
293
+ except Exception:
294
+ pass #收尾失败不掩盖主流程
295
+
296
+
297
+ async def close(self):
298
+
299
+ for mcp_name in list(self.mcp_states):
300
+ await self._drop(mcp_name)
301
+ self.mcp_states.clear()