跳转至内容

平台、MCP 与本地服务

平台提供记忆、知识与 CLI 能力。默认的 bailian 平台封装百炼 CLI 与 MCP 服务;local 将一切保存在磁盘上。AgenticX 也可以向其他 MCP 客户端暴露自身工具(agenticx mcp-server),并提供基于 token 认证的 localhost HTTP API(agenticx serve)。

安装与使用参见安全、平台与 MCP。

平台协议

MemoryProvider

Bases: Protocol

user_id instance-attribute

user_id: str

add async

add(
    messages: list[dict[str, str]],
    custom_content: str = "",
    metadata: dict | None = None,
) -> list[MemoryNode]
Source code in src/dashscope_agenticx/platforms/base.py
104
105
106
107
108
109
110
async def add(
    self,
    messages: list[dict[str, str]],
    custom_content: str = "",
    metadata: dict | None = None,
) -> list[MemoryNode]:
    ...

search async

search(
    query: str | list[dict[str, str]],
    top_k: int = 5,
    min_score: float = 0.3,
) -> list[MemoryNode]
Source code in src/dashscope_agenticx/platforms/base.py
112
113
114
115
116
117
118
async def search(
    self,
    query: str | list[dict[str, str]],
    top_k: int = 5,
    min_score: float = 0.3,
) -> list[MemoryNode]:
    ...

list async

list(
    page_num: int = 1, page_size: int = 10
) -> list[MemoryNode]
Source code in src/dashscope_agenticx/platforms/base.py
120
121
122
123
124
125
async def list(
    self,
    page_num: int = 1,
    page_size: int = 10,
) -> list[MemoryNode]:
    ...

delete async

delete(node_id: str) -> bool
Source code in src/dashscope_agenticx/platforms/base.py
127
128
async def delete(self, node_id: str) -> bool:
    ...

update async

update(node_id: str, content: str) -> bool
Source code in src/dashscope_agenticx/platforms/base.py
130
131
async def update(self, node_id: str, content: str) -> bool:
    ...

MemoryNode dataclass

MemoryNode(
    id: str,
    content: str,
    created_at: str = "",
    updated_at: str = "",
    score: float = 0.0,
    metadata: dict = dict(),
)

id instance-attribute

id: str

content instance-attribute

content: str

created_at class-attribute instance-attribute

created_at: str = ''

updated_at class-attribute instance-attribute

updated_at: str = ''

score class-attribute instance-attribute

score: float = 0.0

metadata class-attribute instance-attribute

metadata: dict = field(default_factory=dict)

MemoryLibrary dataclass

MemoryLibrary(memory_id: str, description: str = '')

memory_id instance-attribute

memory_id: str

description class-attribute instance-attribute

description: str = ''

SearchResult dataclass

SearchResult(
    title: str,
    content: str,
    link: str,
    media: str = "",
    publish_date: str = "",
)

title instance-attribute

title: str

content instance-attribute

content: str
link: str

media class-attribute instance-attribute

media: str = ''

publish_date class-attribute instance-attribute

publish_date: str = ''

KBProvider

Bases: Protocol

list_indices

list_indices(
    page_number: int = 1, page_size: int = 20
) -> list[IndexInfo]
Source code in src/dashscope_agenticx/platforms/base.py
135
136
137
138
139
140
def list_indices(
    self,
    page_number: int = 1,
    page_size: int = 20,
) -> list[IndexInfo]:
    ...

retrieve

retrieve(
    index_id: str,
    query: str,
    top_k: int = 5,
    min_score: float = 0.3,
) -> list[RetrieveNode]
Source code in src/dashscope_agenticx/platforms/base.py
142
143
144
145
146
147
148
149
def retrieve(
    self,
    index_id: str,
    query: str,
    top_k: int = 5,
    min_score: float = 0.3,
) -> list[RetrieveNode]:
    ...

create_index

create_index(
    name: str,
    category_ids: list[str] | None = None,
    document_ids: list[str] | None = None,
    chunk_size: int = 500,
    overlap_size: int = 100,
) -> str
Source code in src/dashscope_agenticx/platforms/base.py
151
152
153
154
155
156
157
158
159
def create_index(
    self,
    name: str,
    category_ids: list[str] | None = None,
    document_ids: list[str] | None = None,
    chunk_size: int = 500,
    overlap_size: int = 100,
) -> str:
    ...

delete_index

delete_index(index_id: str) -> bool
Source code in src/dashscope_agenticx/platforms/base.py
161
162
def delete_index(self, index_id: str) -> bool:
    ...

submit_index_job

submit_index_job(index_id: str) -> str
Source code in src/dashscope_agenticx/platforms/base.py
164
165
def submit_index_job(self, index_id: str) -> str:
    ...

get_index_job_status

get_index_job_status(index_id: str, job_id: str) -> dict
Source code in src/dashscope_agenticx/platforms/base.py
167
168
def get_index_job_status(self, index_id: str, job_id: str) -> dict:
    ...

add_documents_to_index

add_documents_to_index(
    index_id: str,
    category_ids: list[str] | None = None,
    document_ids: list[str] | None = None,
) -> str
Source code in src/dashscope_agenticx/platforms/base.py
170
171
172
173
174
175
176
def add_documents_to_index(
    self,
    index_id: str,
    category_ids: list[str] | None = None,
    document_ids: list[str] | None = None,
) -> str:
    ...

list_index_documents

list_index_documents(
    index_id: str, page_number: int = 1, page_size: int = 20
) -> list[IndexDocument]
Source code in src/dashscope_agenticx/platforms/base.py
178
179
180
181
182
183
184
def list_index_documents(
    self,
    index_id: str,
    page_number: int = 1,
    page_size: int = 20,
) -> list[IndexDocument]:
    ...

delete_index_documents

delete_index_documents(
    index_id: str, document_ids: list[str]
) -> bool
Source code in src/dashscope_agenticx/platforms/base.py
186
187
188
189
190
191
def delete_index_documents(
    self,
    index_id: str,
    document_ids: list[str],
) -> bool:
    ...

DataProvider

Bases: Protocol

upload_file

upload_file(
    file_path: str, category_id: str = "default"
) -> FileInfo
Source code in src/dashscope_agenticx/platforms/base.py
195
196
197
198
199
200
def upload_file(
    self,
    file_path: str,
    category_id: str = "default",
) -> FileInfo:
    ...

list_files

list_files(
    category_id: str = "default", max_results: int = 20
) -> list[FileInfo]
Source code in src/dashscope_agenticx/platforms/base.py
202
203
204
205
206
207
def list_files(
    self,
    category_id: str = "default",
    max_results: int = 20,
) -> list[FileInfo]:
    ...

delete_file

delete_file(
    file_id: str, category_id: str = "default"
) -> bool
Source code in src/dashscope_agenticx/platforms/base.py
209
210
211
212
213
214
def delete_file(
    self,
    file_id: str,
    category_id: str = "default",
) -> bool:
    ...

list_categories

list_categories(
    category_type: str = "UNSTRUCTURED",
) -> list[Category]
Source code in src/dashscope_agenticx/platforms/base.py
216
217
218
219
220
def list_categories(
    self,
    category_type: str = "UNSTRUCTURED",
) -> list[Category]:
    ...

add_category

add_category(
    name: str, category_type: str = "UNSTRUCTURED"
) -> Category
Source code in src/dashscope_agenticx/platforms/base.py
222
223
224
225
226
227
def add_category(
    self,
    name: str,
    category_type: str = "UNSTRUCTURED",
) -> Category:
    ...

PromptProvider

Bases: Protocol

list

list(
    name: str | None = None,
    type: str | None = None,
    max_results: int = 20,
) -> list[PromptTemplate]
Source code in src/dashscope_agenticx/platforms/base.py
231
232
233
234
235
236
237
def list(
    self,
    name: str | None = None,
    type: str | None = None,  # pylint: disable=redefined-builtin
    max_results: int = 20,
) -> list[PromptTemplate]:
    ...

get

get(template_id: str) -> PromptTemplate
Source code in src/dashscope_agenticx/platforms/base.py
239
240
def get(self, template_id: str) -> PromptTemplate:
    ...

create

create(name: str, content: str) -> PromptTemplate
Source code in src/dashscope_agenticx/platforms/base.py
242
243
def create(self, name: str, content: str) -> PromptTemplate:
    ...

update

update(
    template_id: str,
    name: str | None = None,
    content: str | None = None,
) -> bool
Source code in src/dashscope_agenticx/platforms/base.py
245
246
247
248
249
250
251
def update(
    self,
    template_id: str,
    name: str | None = None,
    content: str | None = None,
) -> bool:
    ...

delete

delete(template_id: str) -> bool
Source code in src/dashscope_agenticx/platforms/base.py
253
254
def delete(self, template_id: str) -> bool:
    ...

render

render(template_id: str, variables: dict[str, str]) -> str
Source code in src/dashscope_agenticx/platforms/base.py
256
257
def render(self, template_id: str, variables: dict[str, str]) -> str:
    ...

工厂函数

get_memory_provider

get_memory_provider(config) -> MemoryProvider | None

Always use local file-based memory storage.

Source code in src/dashscope_agenticx/platforms/__init__.py
49
50
51
52
53
54
55
56
57
58
59
60
61
def get_memory_provider(config) -> MemoryProvider | None:
    """Always use local file-based memory storage."""
    user_id = config.memory_user_id
    if not user_id:
        from dashscope_agenticx.utils.ids import stable_memory_user_id

        user_id = stable_memory_user_id()
    from dashscope_agenticx.platforms.local import LocalMemoryClient

    return LocalMemoryClient(
        user_id=user_id,
        memory_library_id=config.memory_library_id,
    )

get_cli_provider

get_cli_provider(config)

Return a BailianCLIClient when the bl binary is on PATH, else None.

bl handles its own auth state (bl auth login or env), but we forward config.tongyi_api_key as the --api-key fallback so a one-config setup just works.

Source code in src/dashscope_agenticx/platforms/__init__.py
64
65
66
67
68
69
70
71
72
73
74
def get_cli_provider(config):
    """Return a BailianCLIClient when the `bl` binary is on PATH, else None.

    `bl` handles its own auth state (`bl auth login` or env), but we forward
    config.tongyi_api_key as the --api-key fallback so a one-config setup just
    works.
    """
    from dashscope_agenticx.platforms.bailian.cli import BailianCLIClient

    client = BailianCLIClient(api_key=config.tongyi_api_key)
    return client if client.available() else None

百炼(Bailian)

BailianCLIClient

BailianCLIClient(
    binary: str = "bl",
    api_key: str = "",
    region: str = "",
    base_url: str = "",
    timeout: int = 180,
)

Subprocess wrapper around the bl binary.

Source code in src/dashscope_agenticx/platforms/bailian/cli.py
56
57
58
59
60
61
62
63
64
65
66
67
68
def __init__(
    self,
    binary: str = "bl",
    api_key: str = "",
    region: str = "",
    base_url: str = "",
    timeout: int = 180,
):
    self.binary = binary
    self.api_key = api_key
    self.region = region
    self.base_url = base_url
    self.timeout = timeout

binary instance-attribute

binary = binary

api_key instance-attribute

api_key = api_key

region instance-attribute

region = region

base_url instance-attribute

base_url = base_url

timeout instance-attribute

timeout = timeout

available

available() -> bool
Source code in src/dashscope_agenticx/platforms/bailian/cli.py
72
73
def available(self) -> bool:
    return shutil.which(self.binary) is not None

export_schemas_sync

export_schemas_sync() -> list[dict]

Synchronous variant — used at startup tool-registration time when we're already inside an event loop and can't spin up another.

Source code in src/dashscope_agenticx/platforms/bailian/cli.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def export_schemas_sync(self) -> list[dict]:
    """Synchronous variant — used at startup tool-registration time when
    we're already inside an event loop and can't spin up another."""
    try:
        cp = subprocess.run(
            [self.binary, "config", "export-schema"],
            capture_output=True,
            text=True,
            timeout=15,
            check=False,
        )
    except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as e:
        raise BailianCLIError(
            f"bl config export-schema failed: {e}",
        ) from e
    if cp.returncode != 0:
        raise BailianCLIError(
            f"bl exit={cp.returncode}: {cp.stderr or cp.stdout}",
        )
    try:
        return json.loads(cp.stdout)
    except json.JSONDecodeError as e:
        raise BailianCLIError(f"bl schema parse failed: {e}") from e

run async

run(
    args: list[str],
    stdin: str = "",
    inject_globals: bool = True,
) -> CLIResult

Run bl <args> and capture stdout/stderr.

Source code in src/dashscope_agenticx/platforms/bailian/cli.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
async def run(
    self,
    args: list[str],
    stdin: str = "",
    inject_globals: bool = True,
) -> CLIResult:
    """Run `bl <args>` and capture stdout/stderr."""
    cmd = [self.binary, *args]
    env = None
    if inject_globals:
        if self.api_key:
            # env, not argv: `--api-key <key>` is visible in `ps` to
            # every local user.
            import os

            env = {**os.environ, "DASHSCOPE_API_KEY": self.api_key}
        if self.region:
            cmd.extend(["--region", self.region])
        if self.base_url:
            cmd.extend(["--base-url", self.base_url])
    proc = await asyncio.create_subprocess_exec(
        *cmd,
        stdin=asyncio.subprocess.PIPE if stdin else None,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        env=env,
    )
    try:
        out, err = await asyncio.wait_for(
            proc.communicate(stdin.encode() if stdin else None),
            timeout=self.timeout,
        )
    except asyncio.TimeoutError:
        proc.kill()
        try:
            await proc.wait()
        except Exception:
            pass
        return CLIResult(
            code=124,
            stdout="",
            stderr=f"timeout ({self.timeout}s)",
        )
    return CLIResult(
        code=proc.returncode or 0,
        stdout=out.decode("utf-8", errors="replace"),
        stderr=err.decode("utf-8", errors="replace"),
    )

invoke async

invoke(command_path: list[str], params: dict) -> str

Translate {kw: val} into --kebab-case <value> flags and call bl.

  • bool=True → --flag
  • bool=False → omitted
  • list → repeat --flag
  • str/number → --flag
  • None → omitted
Source code in src/dashscope_agenticx/platforms/bailian/cli.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
async def invoke(self, command_path: list[str], params: dict) -> str:
    """Translate `{kw: val}` into `--kebab-case <value>` flags and
    call `bl`.

    - bool=True    →  --flag
    - bool=False   →  omitted
    - list         →  repeat --flag <item>
    - str/number   →  --flag <value>
    - None         →  omitted
    """
    args = list(command_path)
    for key, value in params.items():
        if value is None:
            continue
        flag = "--" + _camel_to_kebab(key)
        if isinstance(value, bool):
            if value:
                args.append(flag)
        elif isinstance(value, list):
            for item in value:
                args.extend([flag, str(item)])
        else:
            args.extend([flag, str(value)])

    result = await self.run(args)
    if not result.ok:
        tail = (result.stderr or result.stdout).strip().splitlines()[-20:]
        return f"[bl exit={result.code}]\n" + "\n".join(tail)
    return result.stdout

CLIResult dataclass

CLIResult(code: int, stdout: str, stderr: str)

code instance-attribute

code: int

stdout instance-attribute

stdout: str

stderr instance-attribute

stderr: str

ok property

ok: bool

BailianCLIError

Bases: Exception

MCPClient

MCPClient(service: str, api_key: str, url: str = '')

MCP Client using SSE transport.

Flow: 1. GET /sse — opens SSE stream, server sends 'endpoint' event with POST URL 2. POST to that endpoint — send JSON-RPC requests 3. Server responds via SSE 'message' events on the GET stream

Source code in src/dashscope_agenticx/platforms/bailian/mcp.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def __init__(self, service: str, api_key: str, url: str = ""):
    if not api_key:
        raise MCPError("API key not configured; cannot connect to MCP")
    self.service = service
    base_url = url or f"{BAILIAN_MCP_BASE}/{service}"
    self.sse_url = f"{base_url}/sse"
    self._base_url = base_url
    self._api_key = api_key
    self._headers = {
        "Authorization": f"Bearer {api_key}",
        **dashscope_sdk_headers("mcp", base_url=self._base_url),
    }
    self._client: httpx.AsyncClient | None = None
    self._request_id = 0
    self._message_endpoint: str = ""
    self._pending: dict[int, asyncio.Future] = {}
    self._sse_task: asyncio.Task | None = None
    self._connected = asyncio.Event()
    self.tools: list[dict] = []
    self.prompts: list[dict] = []
    self.last_error: str = ""

service instance-attribute

service = service

sse_url instance-attribute

sse_url = f'{base_url}/sse'

tools instance-attribute

tools: list[dict] = []

prompts instance-attribute

prompts: list[dict] = []

last_error instance-attribute

last_error: str = ''

initialize async

initialize() -> bool
Source code in src/dashscope_agenticx/platforms/bailian/mcp.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
async def initialize(self) -> bool:
    try:
        await self._start_sse()
    except MCPError as e:
        self.last_error = str(e)
        return False
    except httpx.HTTPStatusError as e:
        self.last_error = (
            f"HTTP {e.response.status_code}: {e.response.text[:200]}"
        )
        return False
    except httpx.HTTPError as e:
        self.last_error = str(e)
        return False
    except Exception as e:
        self.last_error = str(e)
        return False

    if self.last_error:
        return False

    params = {
        "protocolVersion": MCP_PROTOCOL_VERSION,
        "clientInfo": {"name": "dashscope-agenticx", "version": "0.1.0"},
        "capabilities": {},
    }
    try:
        resp = await self._send_jsonrpc("initialize", params)
        if isinstance(resp, dict) and "error" in resp:
            self.last_error = resp["error"].get(
                "message",
                str(resp["error"]),
            )
            return False
        await self._send_notification("notifications/initialized")
        return True
    except httpx.HTTPStatusError as e:
        self.last_error = (
            f"HTTP {e.response.status_code}: {e.response.text[:200]}"
        )
        return False
    except httpx.HTTPError as e:
        self.last_error = str(e)
        return False
    except Exception as e:
        self.last_error = str(e)
        return False

list_tools async

list_tools() -> list[dict]
Source code in src/dashscope_agenticx/platforms/bailian/mcp.py
255
256
257
258
259
async def list_tools(self) -> list[dict]:
    resp = await self._send_jsonrpc("tools/list")
    result = resp.get("result", {})
    self.tools = result.get("tools", [])
    return self.tools

list_prompts async

list_prompts() -> list[dict]

Discover available prompts/skills. Returns [] if not supported.

Source code in src/dashscope_agenticx/platforms/bailian/mcp.py
261
262
263
264
265
266
267
268
269
270
271
async def list_prompts(self) -> list[dict]:
    """Discover available prompts/skills. Returns [] if not supported."""
    try:
        resp = await self._send_jsonrpc("prompts/list")
        if isinstance(resp, dict) and "error" in resp:
            return []
        result = resp.get("result", {})
        self.prompts = result.get("prompts", [])
        return self.prompts
    except Exception:
        return []

call_tool async

call_tool(tool_name: str, arguments: dict) -> str
Source code in src/dashscope_agenticx/platforms/bailian/mcp.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
async def call_tool(self, tool_name: str, arguments: dict) -> str:
    params = {"name": tool_name, "arguments": arguments}
    resp = await self._send_jsonrpc("tools/call", params)

    if "error" in resp:
        error = resp["error"]
        return f"MCP Error: {error.get('message', str(error))}"

    result = resp.get("result", {})
    content = result.get("content", [])
    parts = []
    for item in content:
        if isinstance(item, dict):
            if item.get("type") == "text":
                parts.append(item.get("text", ""))
            elif item.get("type") == "image":
                parts.append(f"[image: {item.get('mimeType', 'image')}]")
            else:
                parts.append(str(item))
        else:
            parts.append(str(item))
    return "\n".join(parts) if parts else str(result)

close async

close()
Source code in src/dashscope_agenticx/platforms/bailian/mcp.py
296
297
298
299
300
301
302
303
304
305
306
async def close(self):
    self._fail_all_pending("connection closed")
    if self._sse_task and not self._sse_task.done():
        self._sse_task.cancel()
        try:
            await self._sse_task
        except asyncio.CancelledError:
            pass
    if self._client:
        await self._client.aclose()
        self._client = None

MCPError

Bases: Exception

MCP 服务端模式

通过 MCP stdio 暴露 AgenticX 工具(agenticx mcp-server):

tools_to_mcp_schema

tools_to_mcp_schema() -> list[dict[str, Any]]

Convert registered tools to MCP tool schema format.

Each tool becomes

{ "name": "...", "description": "...", "inputSchema": { ... JSON schema ... } }

Source code in src/dashscope_agenticx/mcp_server.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def tools_to_mcp_schema() -> list[dict[str, Any]]:
    """Convert registered tools to MCP tool schema format.

    Each tool becomes:
        {
            "name": "...",
            "description": "...",
            "inputSchema": { ... JSON schema ... }
        }
    """
    schemas: list[dict[str, Any]] = []
    for tool in registry.list_tools():
        schemas.append(
            {
                "name": tool.name,
                "description": tool.description,
                "inputSchema": tool.parameters,
            },
        )
    return schemas

handle_mcp_request async

handle_mcp_request(
    request: dict[str, Any], executor: Any = None
) -> dict[str, Any]

Handle a single MCP JSON-RPC request.

Supports
  • tools/list: return all registered tools
  • tools/call: execute a tool by name

Returns a JSON-RPC response dict.

Source code in src/dashscope_agenticx/mcp_server.py
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
async def handle_mcp_request(
    request: dict[str, Any],
    executor: Any = None,
) -> dict[str, Any]:
    """Handle a single MCP JSON-RPC request.

    Supports:
      - ``tools/list``: return all registered tools
      - ``tools/call``: execute a tool by name

    Returns a JSON-RPC response dict.
    """
    method = request.get("method", "")
    req_id = request.get("id")
    params = request.get("params", {})

    if method == "tools/list":
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {"tools": tools_to_mcp_schema()},
        }

    if method == "tools/call":
        tool_name = params.get("name")
        arguments = params.get("arguments", {})
        tool_def = registry.get(tool_name)
        if not tool_def:
            return {
                "jsonrpc": "2.0",
                "id": req_id,
                "error": {
                    "code": -32601,
                    "message": f"Unknown tool: {tool_name}",
                },
            }
        try:
            if executor:
                result = await executor.execute(tool_def, arguments)
            else:
                result = tool_def.func(**arguments)
                if hasattr(result, "__await__"):
                    result = await result
            return {
                "jsonrpc": "2.0",
                "id": req_id,
                "result": {"content": [{"type": "text", "text": str(result)}]},
            }
        except Exception as e:
            return {
                "jsonrpc": "2.0",
                "id": req_id,
                "error": {"code": -32603, "message": str(e)},
            }

    if method == "initialize":
        return {
            "jsonrpc": "2.0",
            "id": req_id,
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {"tools": {"listChanged": False}},
                "serverInfo": {
                    "name": "dashscope-agenticx",
                    "version": "0.1.0",
                },
            },
        }

    return {
        "jsonrpc": "2.0",
        "id": req_id,
        "error": {"code": -32601, "message": f"Method not found: {method}"},
    }

run_stdio_server async

run_stdio_server(executor: Any = None) -> None

Run the MCP server on stdio (JSON-RPC over stdin/stdout).

Reads line-delimited JSON requests from stdin, writes responses to stdout.

Source code in src/dashscope_agenticx/mcp_server.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
async def run_stdio_server(executor: Any = None) -> None:
    """Run the MCP server on stdio (JSON-RPC over stdin/stdout).

    Reads line-delimited JSON requests from stdin, writes responses to stdout.
    """
    while True:
        line = sys.stdin.readline()
        if not line:
            break
        line = line.strip()
        if not line:
            continue
        try:
            request = json.loads(line)
        except json.JSONDecodeError:
            response = {
                "jsonrpc": "2.0",
                "id": None,
                "error": {"code": -32700, "message": "Parse error"},
            }
            sys.stdout.write(json.dumps(response) + "\n")
            sys.stdout.flush()
            continue
        # JSON-RPC notifications (requests without an "id") MUST NOT be
        # answered per spec — skip them entirely.
        if "id" not in request:
            continue
        response = await handle_mcp_request(request, executor)
        sys.stdout.write(json.dumps(response) + "\n")
        sys.stdout.flush()

main

main() -> None

Entry point for agenticx mcp-server: run the MCP stdio server.

Registers the builtin tools (same set the CLI imports at startup) and serves JSON-RPC over stdin/stdout. There is no interactive user at the console in this mode, so the executor auto-approves tool calls.

Source code in src/dashscope_agenticx/mcp_server.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def main() -> None:
    """Entry point for ``agenticx mcp-server``: run the MCP stdio server.

    Registers the builtin tools (same set the CLI imports at startup) and
    serves JSON-RPC over stdin/stdout. There is no interactive user at the
    console in this mode, so the executor auto-approves tool calls.
    """
    import asyncio

    import dashscope_agenticx.tools.browser  # noqa: F401
    import dashscope_agenticx.tools.camera  # noqa: F401
    import dashscope_agenticx.tools.filesystem  # noqa: F401
    import dashscope_agenticx.tools.shell  # noqa: F401
    import dashscope_agenticx.tools.web_search  # noqa: F401
    from dashscope_agenticx.executor import Executor

    asyncio.run(run_stdio_server(executor=Executor(auto_approve=True)))

StdioMCPClient

StdioMCPClient(
    command: str,
    args: list[str] | None = None,
    timeout: float = 30.0,
)

MCP client that drives a local server over stdio.

The server process is spawned with command + args; requests and responses are single-line JSON documents. A background reader matches response ids to pending request futures; server notifications (messages without an id) are ignored.

Source code in src/dashscope_agenticx/mcp_stdio.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def __init__(
    self,
    command: str,
    args: list[str] | None = None,
    timeout: float = 30.0,
):
    if not command:
        raise MCPError("stdio MCP server requires a command")
    self.command = command
    self.args = list(args or [])
    self.timeout = timeout
    self.tools: list[dict] = []
    self.prompts: list[dict] = []
    self.last_error = ""
    self._proc: asyncio.subprocess.Process | None = None
    self._reader_task: asyncio.Task | None = None
    self._pending: dict[int, asyncio.Future] = {}
    self._request_id = 0
    self._stderr_tail = ""

command instance-attribute

command = command

args instance-attribute

args = list(args or [])

timeout instance-attribute

timeout = timeout

tools instance-attribute

tools: list[dict] = []

prompts instance-attribute

prompts: list[dict] = []

last_error instance-attribute

last_error = ''

initialize async

initialize() -> bool

Spawn the server, run the MCP initialize handshake.

Source code in src/dashscope_agenticx/mcp_stdio.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
async def initialize(self) -> bool:
    """Spawn the server, run the MCP initialize handshake."""
    try:
        self._proc = await asyncio.create_subprocess_exec(
            self.command,
            *self.args,
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
    except (OSError, ValueError) as exc:
        self.last_error = f"Failed to start MCP server: {exc}"
        return False

    self._reader_task = asyncio.create_task(self._read_loop())

    params = {
        "protocolVersion": MCP_PROTOCOL_VERSION,
        "capabilities": {},
        "clientInfo": dict(_CLIENT_INFO),
    }
    try:
        resp = await self._request("initialize", params)
    except MCPError as exc:
        self.last_error = str(exc)
        await self.close()
        return False
    if "error" in resp:
        error = resp["error"]
        message = error.get("message", str(error))
        self.last_error = f"MCP initialize failed: {message}"
        await self.close()
        return False
    try:
        await self._notify("notifications/initialized")
    except MCPError as exc:
        self.last_error = str(exc)
        await self.close()
        return False
    return True

close async

close() -> None

Stop the reader, close stdin, terminate the subprocess.

Source code in src/dashscope_agenticx/mcp_stdio.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
async def close(self) -> None:
    """Stop the reader, close stdin, terminate the subprocess."""
    self._fail_all_pending("connection closed")
    if self._reader_task and not self._reader_task.done():
        self._reader_task.cancel()
        try:
            await self._reader_task
        except (asyncio.CancelledError, Exception):
            pass
    self._reader_task = None

    proc = self._proc
    self._proc = None
    if proc is None:
        return
    if proc.stdin and not proc.stdin.is_closing():
        try:
            proc.stdin.close()
        except (OSError, RuntimeError):
            pass
    if proc.returncode is None:
        try:
            await asyncio.wait_for(proc.wait(), timeout=_CLOSE_TIMEOUT)
        except asyncio.TimeoutError:
            try:
                proc.terminate()
                await asyncio.wait_for(
                    proc.wait(),
                    timeout=_CLOSE_TIMEOUT,
                )
            except (asyncio.TimeoutError, ProcessLookupError, OSError):
                try:
                    proc.kill()
                except (ProcessLookupError, OSError):
                    pass
    await self._drain_stderr(proc)

list_tools async

list_tools() -> list[dict]
Source code in src/dashscope_agenticx/mcp_stdio.py
142
143
144
145
146
147
148
149
150
async def list_tools(self) -> list[dict]:
    resp = await self._request("tools/list")
    if "error" in resp:
        error = resp["error"]
        message = error.get("message", str(error))
        raise MCPError(f"tools/list failed: {message}")
    result = resp.get("result", {})
    self.tools = result.get("tools", [])
    return self.tools

list_prompts async

list_prompts() -> list[dict]

Discover prompts/skills; returns [] when unsupported.

Source code in src/dashscope_agenticx/mcp_stdio.py
152
153
154
155
156
157
158
159
160
161
162
async def list_prompts(self) -> list[dict]:
    """Discover prompts/skills; returns [] when unsupported."""
    try:
        resp = await self._request("prompts/list")
    except MCPError:
        return []
    if "error" in resp:
        return []
    result = resp.get("result", {})
    self.prompts = result.get("prompts", [])
    return self.prompts

call_tool async

call_tool(tool_name: str, arguments: dict) -> str
Source code in src/dashscope_agenticx/mcp_stdio.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
async def call_tool(self, tool_name: str, arguments: dict) -> str:
    params = {"name": tool_name, "arguments": arguments}
    resp = await self._request("tools/call", params)
    if "error" in resp:
        error = resp["error"]
        message = error.get("message", str(error))
        return f"MCP Error: {message}"
    result = resp.get("result", {})
    content = result.get("content", [])
    parts: list[str] = []
    for item in content:
        if isinstance(item, dict) and item.get("type") == "text":
            parts.append(str(item.get("text", "")))
        else:
            parts.append(json.dumps(item, ensure_ascii=False))
    return "\n".join(parts) if parts else str(result)

本地 HTTP API

agenticx serve 仅绑定 localhost 并要求 bearer token;非 localhost 的绑定地址会被拒绝。

LocalAPI

LocalAPI(
    token: str,
    *,
    session_manager: SessionManager | None = None,
    run_handler: RunHandler | None = None,
    trace_dir: Path | None = None
)
Source code in src/dashscope_agenticx/server.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def __init__(
    self,
    token: str,
    *,
    session_manager: SessionManager | None = None,
    run_handler: RunHandler | None = None,
    trace_dir: Path | None = None,
):
    if len(token) < 16:
        raise ValueError(
            "localhost server token must be at least 16 chars",
        )
    self.token = token
    self.session_manager = session_manager or SessionManager()
    self.run_handler = run_handler or _default_run
    self.trace_dir = trace_dir or (WORKSPACE_DIR / "traces")

token instance-attribute

token = token

session_manager instance-attribute

session_manager = session_manager or SessionManager()

run_handler instance-attribute

run_handler = run_handler or _default_run

trace_dir instance-attribute

trace_dir = trace_dir or WORKSPACE_DIR / 'traces'

authorized

authorized(header: str) -> bool
Source code in src/dashscope_agenticx/server.py
89
90
91
92
93
94
def authorized(self, header: str) -> bool:
    expected = f"Bearer {self.token}"
    return hmac.compare_digest(
        (header or "").encode("utf-8"),
        expected.encode("utf-8"),
    )

get

get(path: str) -> tuple[int, dict[str, Any]]
Source code in src/dashscope_agenticx/server.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def get(self, path: str) -> tuple[int, dict[str, Any]]:
    parsed = urlparse(path)
    if parsed.path == "/health":
        return 200, {"status": "ok"}
    if parsed.path == "/v1/sessions":
        return 200, {
            "sessions": [
                meta.to_dict()
                for meta in self.session_manager.list_topics()
            ],
        }
    if parsed.path.startswith("/v1/sessions/"):
        topic = parsed.path.rsplit("/", 1)[-1]
        try:
            state = self.session_manager.project_state(topic)
        except ValueError:
            return 400, {"error": "invalid session"}
        return 200, sanitize(state)
    if parsed.path == "/v1/artifacts":
        topic = parse_qs(parsed.query).get("session_id", ["default"])[0]
        return 200, {
            "artifacts": self.session_manager.project_state(topic).get(
                "artifacts",
                [],
            ),
        }
    if parsed.path == "/v1/traces":
        traces = []
        if self.trace_dir.is_dir():
            traces = [
                path.name
                for path in sorted(self.trace_dir.glob("*.jsonl"))[-100:]
            ]
        return 200, {"traces": traces}
    return 404, {"error": "not found"}

post

post(
    path: str, payload: dict[str, Any]
) -> tuple[int, dict[str, Any]]
Source code in src/dashscope_agenticx/server.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def post(
    self,
    path: str,
    payload: dict[str, Any],
) -> tuple[int, dict[str, Any]]:
    if path == "/v1/runs":
        if not payload.get("input"):
            return 400, {"error": "input is required"}
        try:
            return 200, sanitize(self.run_handler(payload))
        except Exception as exc:
            return 500, sanitize(
                {"error": type(exc).__name__, "message": str(exc)},
            )
    if path.startswith("/v1/permissions"):
        return 403, {
            "error": "permission decisions are local-runtime only",
        }
    return 404, {"error": "not found"}

create_server

create_server(
    host: str = "127.0.0.1",
    port: int = 8765,
    *,
    token: str,
    api: LocalAPI | None = None
) -> ThreadingHTTPServer
Source code in src/dashscope_agenticx/server.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def create_server(
    host: str = "127.0.0.1",
    port: int = 8765,
    *,
    token: str,
    api: LocalAPI | None = None,
) -> ThreadingHTTPServer:
    if host not in {"127.0.0.1", "localhost", "::1"}:
        raise ValueError("AgenticX serve only binds to localhost")
    local_api = api or LocalAPI(token)

    class Handler(BaseHTTPRequestHandler):
        def _json(self, status: int, payload: dict[str, Any]) -> None:
            body = json.dumps(sanitize(payload), ensure_ascii=False).encode(
                "utf-8",
            )
            self.send_response(status)
            self.send_header("Content-Type", "application/json; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def _authorized(self) -> bool:
            if local_api.authorized(self.headers.get("Authorization", "")):
                return True
            self._json(401, {"error": "unauthorized"})
            return False

        def do_GET(self):  # noqa: N802
            if not self._authorized():
                return
            status, payload = local_api.get(self.path)
            self._json(status, payload)

        def do_POST(self):  # noqa: N802
            if not self._authorized():
                return
            try:
                size = int(self.headers.get("Content-Length", "0"))
                if size < 0:
                    raise ValueError("negative content length")
                if size > 1_000_000:
                    self._json(413, {"error": "request body too large"})
                    return
                self.connection.settimeout(30)
                payload = json.loads(self.rfile.read(size) or b"{}")
                if not isinstance(payload, dict):
                    raise ValueError("JSON body must be an object")
            except (ValueError, json.JSONDecodeError):
                self._json(400, {"error": "invalid JSON"})
                return
            status, result = local_api.post(urlparse(self.path).path, payload)
            self._json(status, result)

        def log_message(self, fmt, *args):
            del fmt, args

    class Server(ThreadingHTTPServer):
        address_family = socket.AF_INET6 if host == "::1" else socket.AF_INET

    return Server((host, port), Handler)

serve

serve(
    host: str = "127.0.0.1",
    port: int = 8765,
    token: str = "",
) -> None
Source code in src/dashscope_agenticx/server.py
216
217
218
219
220
221
222
223
224
225
226
227
228
def serve(
    host: str = "127.0.0.1",
    port: int = 8765,
    token: str = "",
) -> None:
    token = token or generate_server_token()
    server = create_server(host, port, token=token)
    print(f"AgenticX server: http://{host}:{server.server_port}")
    print(f"Bearer token: {token}")
    try:
        server.serve_forever()
    finally:
        server.server_close()

generate_server_token

generate_server_token() -> str
Source code in src/dashscope_agenticx/server.py
25
26
def generate_server_token() -> str:
    return secrets.token_urlsafe(32)