- 授权闭环 4 工具:authorize.grant / revoke / effective(四源并集 + 应用过滤两组数)+ user.create —— effective 是「授权了但看不见」的唯一诊断入口;user.create 建非管理员账号让闭环可自证 - prompts 3 模板:new_business_module / diagnose_menu_not_visible / verify_all —— 测试核对模板里引用的工具 id 是否存在(防腐烂) - 新 crate sspf-adapter-baseline:PlatformAdapter 第二实现,5 个只读 op + 形状归一化 —— 用 hyper::client::conn::http1,只支持 http://,口令传密文 - 新增 AR6 与 baseline-smoke.sh(10 条);mcp-smoke 23 → 32 条 - 影响:测试 282 → 306;十一闸全绿;工具 15 → 19;内存仍 7 MB
628 lines
23 KiB
Rust
628 lines
23 KiB
Rust
//! server —— MCP 协议主循环(stdio / NDJSON)。
|
||
//!
|
||
//! ## 只实现 6 个方法
|
||
//!
|
||
//! | 方法 | 作用 |
|
||
//! |---|---|
|
||
//! | `initialize` | 握手,报 capabilities |
|
||
//! | `notifications/initialized` | 通知,不回复 |
|
||
//! | `tools/list` | **只返回 4 个元工具** |
|
||
//! | `tools/call` | 执行元工具(业务工具经 `sspf_call` 间接执行) |
|
||
//! | `resources/list` / `resources/read` | 契约、DDL、错误码字典等只读资料 |
|
||
//! | `prompts/list` / `prompts/get` | 多步流程模板 |
|
||
//! | `ping` | 保活 |
|
||
//!
|
||
//! ## 🔴 协议层永远只见 4 个工具
|
||
//!
|
||
//! 这是 token 预算的实现方式:`tools/list` 返回 4 条,AI 要看别的就 `sspf_discover`。
|
||
//! 加业务工具**不会**让 `tools/list` 变长。
|
||
|
||
use std::sync::Arc;
|
||
|
||
use serde_json::{json, Value};
|
||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||
|
||
use crate::adapter::PlatformAdapter;
|
||
use crate::jsonrpc::{self, codes, Incoming};
|
||
use crate::registry::Registry;
|
||
use crate::tools::meta::META_TOOLS;
|
||
|
||
/// 协议版本(MCP spec 的日期版本号)。
|
||
const PROTOCOL_VERSION: &str = "2025-06-18";
|
||
|
||
/// MCP 服务。
|
||
pub struct Server {
|
||
adapter: Arc<dyn PlatformAdapter>,
|
||
/// 是否收到过 `initialize`(未握手就调工具是客户端 bug,但我们不硬拦)。
|
||
initialized: bool,
|
||
}
|
||
|
||
impl Server {
|
||
/// 用给定适配器构造。
|
||
pub fn new(adapter: Arc<dyn PlatformAdapter>) -> Self {
|
||
Self {
|
||
adapter,
|
||
initialized: false,
|
||
}
|
||
}
|
||
|
||
/// 跑 stdio 主循环,直到 stdin 关闭。
|
||
///
|
||
/// 🔴 **调用方要保证 stdout 干净**:内嵌数据库(pglite / PG)会往 fd 1 打日志,
|
||
/// 混进 NDJSON 会让客户端解析失败。内核侧的做法见 `main.rs` 的
|
||
/// `redirect_stdout_to_stderr()`(把 fd 1 指向 stderr,协议走复制出来的 fd)。
|
||
pub async fn serve_stdio(self) -> std::io::Result<()> {
|
||
let stdin = tokio::io::stdin();
|
||
let stdout = tokio::io::stdout();
|
||
self.serve(stdin, stdout).await
|
||
}
|
||
|
||
/// MCP 生产入口:**单线程串行**读-处理-写(blocking 线程里 `block_on`)。
|
||
///
|
||
/// 🔴 为什么不是「读线程 + channel + 异步主循环」:
|
||
/// 实测后者在请求条数变化时会**偶发丢整个批次**(同一条命令,有时 0 条响应、
|
||
/// 有时全在)—— 根因是 channel 关闭与主循环退出的时序竞争,排查成本远高于收益。
|
||
///
|
||
/// MCP 是**单会话串行**协议,本来不需要并发读。一个线程读到尾最稳;
|
||
/// `block_on` 在 `spawn_blocking` 线程里是安全的(不在 runtime worker 上)。
|
||
///
|
||
/// 🔴 为什么不用 `tokio::io::stdin()`:内嵌 PostgreSQL 的 single-user 后端会占用 fd 0,
|
||
/// 直接读 stdin 会拿到 `ENXIO (Device not configured)`。
|
||
/// 内核侧在开库前用 `dup` 把协议通道复制出来(见 `main.rs::detach_stdio_for_mcp`)。
|
||
pub async fn serve_blocking_stdin<R, W>(
|
||
mut self,
|
||
reader: R,
|
||
mut writer: W,
|
||
) -> std::io::Result<()>
|
||
where
|
||
R: std::io::Read + Send + 'static,
|
||
W: std::io::Write + Send + 'static,
|
||
{
|
||
let handle = tokio::runtime::Handle::current();
|
||
|
||
tokio::task::spawn_blocking(move || -> std::io::Result<()> {
|
||
use std::io::BufRead;
|
||
|
||
let mut reader = std::io::BufReader::new(reader);
|
||
let mut buf: Vec<u8> = Vec::new();
|
||
|
||
loop {
|
||
buf.clear();
|
||
// 🔴 用 `read_until` 而不是 `read_line`:后者对**非 UTF-8 字节**返回
|
||
// `InvalidData` 错误,会让整个主循环以 Err 退出 —— 表现为「一条响应都没有」。
|
||
// JSON 是 UTF-8,但客户端/终端在极端情况下可能混入 BOM 或截断字节。
|
||
let n = reader
|
||
.read_until(b'\n', &mut buf)
|
||
.map_err(|e| std::io::Error::new(e.kind(), format!("读协议通道失败: {e}")))?;
|
||
if n == 0 {
|
||
break; // EOF
|
||
}
|
||
|
||
let text = String::from_utf8_lossy(&buf);
|
||
let text = text.trim();
|
||
if text.is_empty() {
|
||
continue;
|
||
}
|
||
|
||
let reply = match Incoming::parse(text) {
|
||
Ok(msg) => handle.block_on(self.handle(msg)),
|
||
Err((code, message)) => Some(jsonrpc::error(Value::Null, code, message)),
|
||
};
|
||
|
||
if let Some(v) = reply {
|
||
let mut buf = serde_json::to_vec(&v)?;
|
||
buf.push(b'\n');
|
||
writer.write_all(&buf).map_err(|e| {
|
||
std::io::Error::new(e.kind(), format!("写协议通道失败: {e}"))
|
||
})?;
|
||
writer.flush().map_err(|e| {
|
||
std::io::Error::new(e.kind(), format!("flush 协议通道失败: {e}"))
|
||
})?;
|
||
}
|
||
}
|
||
|
||
Ok(())
|
||
})
|
||
.await
|
||
.map_err(|e| std::io::Error::other(format!("MCP 主循环任务失败: {e}")))?
|
||
}
|
||
|
||
/// 用任意异步读写流跑主循环(**测试用**;生产走 [`serve_blocking_stdin`])。
|
||
pub async fn serve<R, W>(mut self, reader: R, mut writer: W) -> std::io::Result<()>
|
||
where
|
||
R: tokio::io::AsyncRead + Unpin,
|
||
W: tokio::io::AsyncWrite + Unpin,
|
||
{
|
||
let mut reader = BufReader::new(reader).lines();
|
||
|
||
while let Some(line) = reader.next_line().await.map_err(|e| {
|
||
std::io::Error::new(e.kind(), format!("读 stdin 失败(NDJSON 帧): {e}"))
|
||
})? {
|
||
let line = line.trim();
|
||
if line.is_empty() {
|
||
continue;
|
||
}
|
||
|
||
let reply = match Incoming::parse(line) {
|
||
Ok(msg) => self.handle(msg).await,
|
||
Err((code, message)) => {
|
||
// 解析失败时拿不到 id ⇒ 用 null(JSON-RPC 允许)
|
||
Some(jsonrpc::error(Value::Null, code, message))
|
||
}
|
||
};
|
||
|
||
if let Some(v) = reply {
|
||
let mut buf = serde_json::to_vec(&v)?;
|
||
buf.push(b'\n');
|
||
writer.write_all(&buf).await.map_err(|e| {
|
||
std::io::Error::new(e.kind(), format!("写协议通道失败: {e}"))
|
||
})?;
|
||
writer.flush().await.map_err(|e| {
|
||
std::io::Error::new(e.kind(), format!("flush 协议通道失败: {e}"))
|
||
})?;
|
||
}
|
||
}
|
||
|
||
Ok(())
|
||
}
|
||
|
||
/// 处理一条消息;返回 `None` 表示这是通知,不回复。
|
||
pub async fn handle(&mut self, msg: Incoming) -> Option<Value> {
|
||
let id = match &msg.id {
|
||
Some(id) => id.clone(),
|
||
None => {
|
||
// 通知:只有 initialized 需要处理(记状态),其余忽略
|
||
if msg.method == "notifications/initialized" {
|
||
self.initialized = true;
|
||
}
|
||
return None;
|
||
}
|
||
};
|
||
|
||
let result = match msg.method.as_str() {
|
||
"initialize" => Ok(self.on_initialize()),
|
||
"ping" => Ok(json!({})),
|
||
"tools/list" => Ok(self.on_tools_list()),
|
||
"tools/call" => self.on_tools_call(msg.params).await,
|
||
"resources/list" => Ok(self.on_resources_list()),
|
||
"resources/read" => self.on_resources_read(msg.params),
|
||
"prompts/list" => Ok(on_prompts_list()),
|
||
"prompts/get" => on_prompts_get(msg.params),
|
||
other => Err((
|
||
codes::METHOD_NOT_FOUND,
|
||
format!("不支持的方法: {other}"),
|
||
)),
|
||
};
|
||
|
||
Some(match result {
|
||
Ok(v) => jsonrpc::success(id, v),
|
||
Err((code, message)) => jsonrpc::error(id, code, message),
|
||
})
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 各方法
|
||
|
||
fn on_initialize(&self) -> Value {
|
||
json!({
|
||
"protocolVersion": PROTOCOL_VERSION,
|
||
"capabilities": {
|
||
"tools": { "listChanged": false },
|
||
"resources": { "subscribe": false, "listChanged": false },
|
||
"prompts": { "listChanged": false }
|
||
},
|
||
"serverInfo": {
|
||
"name": "sspf-mcp",
|
||
"version": crate::VERSION,
|
||
},
|
||
"instructions": concat!(
|
||
"SSPF 开发平台工具层。\n",
|
||
"第一步永远调 sspf_context 拿环境;\n",
|
||
"不知道用哪个工具就 sspf_discover(返回精简索引,约 20 token/条);\n",
|
||
"第一次用一个工具先 sspf_describe(level=\"pitfalls\")——",
|
||
"平台的隐式约束(坑)比参数形状更常导致失败;\n",
|
||
"执行统一走 sspf_call,失败时读 error.hints 与 error.next_actions 自纠,",
|
||
"不要原样重试。"
|
||
),
|
||
})
|
||
}
|
||
|
||
fn on_tools_list(&self) -> Value {
|
||
let tools: Vec<Value> = META_TOOLS.iter().map(|t| t.to_mcp_tool()).collect();
|
||
json!({ "tools": tools })
|
||
}
|
||
|
||
async fn on_tools_call(&self, params: Value) -> Result<Value, (i32, String)> {
|
||
let name = params
|
||
.get("name")
|
||
.and_then(Value::as_str)
|
||
.ok_or_else(|| (codes::INVALID_PARAMS, "缺少 name".to_string()))?;
|
||
|
||
let args = params
|
||
.get("arguments")
|
||
.cloned()
|
||
.unwrap_or_else(|| json!({}));
|
||
|
||
let Some(tool) = META_TOOLS.iter().find(|t| t.id == name) else {
|
||
return Err((
|
||
codes::INVALID_PARAMS,
|
||
format!("未知工具 {name}(本层只暴露 4 个元工具;业务工具请用 sspf_call)"),
|
||
));
|
||
};
|
||
|
||
match (tool.handler)(self.adapter.as_ref(), args).await {
|
||
Ok(data) => Ok(json!({
|
||
"content": [{
|
||
"type": "text",
|
||
"text": serde_json::to_string_pretty(&data).unwrap_or_else(|_| "{}".into())
|
||
}],
|
||
"structuredContent": data,
|
||
"isError": false
|
||
})),
|
||
Err(e) => Ok(json!({
|
||
"content": [{ "type": "text", "text": e.message.clone() }],
|
||
"structuredContent": e,
|
||
"isError": true
|
||
})),
|
||
}
|
||
}
|
||
|
||
fn on_resources_list(&self) -> Value {
|
||
let reg = Registry::global();
|
||
json!({
|
||
"resources": [
|
||
{
|
||
"uri": "sspf://registry/tools",
|
||
"name": "全部工具索引",
|
||
"description": format!("当前 {} 个业务工具的完整清单(id / 分类 / 一句话)", reg.all().len()),
|
||
"mimeType": "application/json"
|
||
},
|
||
{
|
||
"uri": "sspf://docs/quickstart",
|
||
"name": "快速上手",
|
||
"description": "元工具的推荐调用顺序与常见误区",
|
||
"mimeType": "text/markdown"
|
||
},
|
||
{
|
||
"uri": "sspf://contract/endpoints",
|
||
"name": "HTTP 契约端点表",
|
||
"description": "内核实现的 HTTP 端点(与 MCP 工具不是一一对应)",
|
||
"mimeType": "text/markdown"
|
||
}
|
||
]
|
||
})
|
||
}
|
||
|
||
fn on_resources_read(&self, params: Value) -> Result<Value, (i32, String)> {
|
||
let uri = params
|
||
.get("uri")
|
||
.and_then(Value::as_str)
|
||
.ok_or_else(|| (codes::INVALID_PARAMS, "缺少 uri".to_string()))?;
|
||
|
||
let text = match uri {
|
||
"sspf://registry/tools" => {
|
||
let reg = Registry::global();
|
||
let list: Vec<Value> = reg
|
||
.all()
|
||
.iter()
|
||
.map(|t| {
|
||
json!({
|
||
"id": t.id,
|
||
"title": t.title,
|
||
"category": t.category.as_str(),
|
||
"one_liner": t.one_liner,
|
||
"read_only": t.annotations.read_only,
|
||
})
|
||
})
|
||
.collect();
|
||
serde_json::to_string_pretty(&json!({
|
||
"count": list.len(),
|
||
"tools": list
|
||
}))
|
||
.unwrap_or_default()
|
||
}
|
||
"sspf://docs/quickstart" => QUICKSTART.to_string(),
|
||
"sspf://contract/endpoints" => {
|
||
"见仓库 docs/contract.md(机器可读附录 A);本资源 P1 后续接文件系统读取。"
|
||
.to_string()
|
||
}
|
||
other => {
|
||
return Err((
|
||
codes::INVALID_PARAMS,
|
||
format!("未知资源 {other}(先 resources/list)"),
|
||
))
|
||
}
|
||
};
|
||
|
||
Ok(json!({
|
||
"contents": [{ "uri": uri, "mimeType": "text/plain", "text": text }]
|
||
}))
|
||
}
|
||
}
|
||
|
||
/// `prompts/list` —— 列出全部多步流程模板。
|
||
///
|
||
/// 模板不占常驻 token:客户端只在用户主动引用时才 `prompts/get`。
|
||
fn on_prompts_list() -> Value {
|
||
let list: Vec<Value> = crate::prompts::PROMPTS
|
||
.iter()
|
||
.map(|p| {
|
||
json!({
|
||
"name": p.name,
|
||
"title": p.title,
|
||
"description": p.description,
|
||
"arguments": p.arguments.iter().map(|a| json!({
|
||
"name": a.name,
|
||
"description": a.description,
|
||
"required": a.required,
|
||
})).collect::<Vec<_>>(),
|
||
})
|
||
})
|
||
.collect();
|
||
json!({ "prompts": list })
|
||
}
|
||
|
||
/// `prompts/get` —— 渲染一个模板。
|
||
///
|
||
/// 🔴 必填参数缺失 ⇒ `INVALID_PARAMS`:模板正文会带着 `<参数名>` 占位符发出去,
|
||
/// AI 会照着字面量去执行(拿到 `<module_code>` 这种值),比直接报错更糟。
|
||
fn on_prompts_get(params: Value) -> Result<Value, (i32, String)> {
|
||
let name = params
|
||
.get("name")
|
||
.and_then(Value::as_str)
|
||
.ok_or_else(|| (codes::INVALID_PARAMS, "缺少 name".to_string()))?;
|
||
|
||
let Some(p) = crate::prompts::find(name) else {
|
||
let avail: Vec<&str> = crate::prompts::PROMPTS.iter().map(|x| x.name).collect();
|
||
return Err((
|
||
codes::INVALID_PARAMS,
|
||
format!("未知模板 {name};可用:{}", avail.join(" / ")),
|
||
));
|
||
};
|
||
|
||
let mut args: std::collections::BTreeMap<String, String> =
|
||
std::collections::BTreeMap::new();
|
||
if let Some(obj) = params.get("arguments").and_then(Value::as_object) {
|
||
for (k, v) in obj {
|
||
if let Some(s) = v.as_str() {
|
||
args.insert(k.clone(), s.to_string());
|
||
}
|
||
}
|
||
}
|
||
|
||
let missing: Vec<&str> = p
|
||
.arguments
|
||
.iter()
|
||
.filter(|a| a.required && !args.contains_key(a.name))
|
||
.map(|a| a.name)
|
||
.collect();
|
||
if !missing.is_empty() {
|
||
return Err((
|
||
codes::INVALID_PARAMS,
|
||
format!("模板 {name} 缺少必填参数:{}", missing.join(", ")),
|
||
));
|
||
}
|
||
|
||
Ok(json!({
|
||
"description": p.description,
|
||
"messages": [{
|
||
"role": "user",
|
||
"content": { "type": "text", "text": (p.render)(&args) }
|
||
}]
|
||
}))
|
||
}
|
||
|
||
/// `sspf://docs/quickstart` 的内容。
|
||
const QUICKSTART: &str = r#"# SSPF 工具层快速上手
|
||
|
||
## 推荐顺序
|
||
|
||
1. `sspf_context` —— 确认后端、应用、用户
|
||
2. `sspf_discover` —— 按意图搜工具(不传参返回分类树)
|
||
3. `sspf_describe(level="pitfalls")` —— 先看坑,参数不确定再 `level="full"`
|
||
4. `sspf_call(dry_run=true)` —— 校验形态
|
||
5. `sspf_call` —— 真执行
|
||
|
||
## 三个常见误区
|
||
|
||
- **跳过 context 直接调工具**:多应用下菜单/权限按 `f_system_id` 隔离,
|
||
app_code 不对时表现成「菜单是空的」,不报错。
|
||
- **失败后原样重试**:业务失败是确定性的(enCode 重复、无权限)。
|
||
读 `error.hints` 和 `error.next_actions`,按建议改。
|
||
- **一次传一长串需求当 query**:检索是 AND 语义,长句反而搜不到。拆成 2-4 个关键词。
|
||
|
||
## 工具 id 的形态
|
||
|
||
`域.动作`,如 `form.create`、`schema.table.list`。
|
||
域取值:context / schema / model / form / menu / permission / dict / data / workflow / verify / release / ops。
|
||
"#;
|
||
|
||
/// 把同步 `Write` 包成 `AsyncWrite`。
|
||
///
|
||
/// 🔴 为什么需要它:MCP 模式下协议通道是一条**复制出来的 fd**(见内核 `main.rs`
|
||
/// 的 `redirect_stdout_to_stderr`)。`tokio::fs::File` 只支持普通文件,
|
||
/// 对管道 / 字符设备会返回 `ENXIO (Device not configured)`。
|
||
///
|
||
/// 阻塞写在这里是可接受的:MCP 一条消息几百字节到几 KB,写管道几乎瞬时;
|
||
/// 而且单会话串行处理,不存在并发争用。
|
||
pub struct BlockingWriter<W> {
|
||
inner: W,
|
||
}
|
||
|
||
impl<W> BlockingWriter<W> {
|
||
/// 包装一个同步 writer。
|
||
pub fn new(inner: W) -> Self {
|
||
Self { inner }
|
||
}
|
||
}
|
||
|
||
impl<W: std::io::Write + Unpin> tokio::io::AsyncWrite for BlockingWriter<W> {
|
||
fn poll_write(
|
||
self: std::pin::Pin<&mut Self>,
|
||
_cx: &mut std::task::Context<'_>,
|
||
buf: &[u8],
|
||
) -> std::task::Poll<std::io::Result<usize>> {
|
||
let this = self.get_mut();
|
||
std::task::Poll::Ready(this.inner.write(buf))
|
||
}
|
||
|
||
fn poll_flush(
|
||
self: std::pin::Pin<&mut Self>,
|
||
_cx: &mut std::task::Context<'_>,
|
||
) -> std::task::Poll<std::io::Result<()>> {
|
||
let this = self.get_mut();
|
||
std::task::Poll::Ready(this.inner.flush())
|
||
}
|
||
|
||
fn poll_shutdown(
|
||
self: std::pin::Pin<&mut Self>,
|
||
_cx: &mut std::task::Context<'_>,
|
||
) -> std::task::Poll<std::io::Result<()>> {
|
||
let this = self.get_mut();
|
||
std::task::Poll::Ready(this.inner.flush())
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::adapter::NullAdapter;
|
||
|
||
fn server() -> Server {
|
||
Server::new(Arc::new(NullAdapter::new("native-test")))
|
||
}
|
||
|
||
fn req(id: i64, method: &str, params: Value) -> Incoming {
|
||
Incoming {
|
||
id: Some(json!(id)),
|
||
method: method.to_string(),
|
||
params,
|
||
}
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn initialize_reports_capabilities_and_instructions() {
|
||
let mut s = server();
|
||
let v = s.handle(req(1, "initialize", json!({}))).await.unwrap();
|
||
assert_eq!(v["result"]["protocolVersion"], PROTOCOL_VERSION);
|
||
assert!(v["result"]["capabilities"]["tools"].is_object());
|
||
assert!(v["result"]["instructions"].as_str().unwrap().contains("sspf_context"));
|
||
}
|
||
|
||
/// 🔴 协议层只能看到 4 个工具 —— 这是 token 预算的硬约束。
|
||
#[tokio::test]
|
||
async fn tools_list_returns_only_four_meta_tools() {
|
||
let mut s = server();
|
||
let v = s.handle(req(2, "tools/list", json!({}))).await.unwrap();
|
||
let tools = v["result"]["tools"].as_array().unwrap();
|
||
assert_eq!(tools.len(), 4, "元工具只能是 4 个");
|
||
let names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect();
|
||
for expected in ["sspf_context", "sspf_discover", "sspf_describe", "sspf_call"] {
|
||
assert!(names.contains(&expected), "缺元工具 {expected}");
|
||
}
|
||
}
|
||
|
||
/// 业务工具**不能**出现在 tools/list 里(否则分层加载失效)。
|
||
#[tokio::test]
|
||
async fn business_tools_are_not_exposed_via_tools_list() {
|
||
let mut s = server();
|
||
let v = s.handle(req(3, "tools/list", json!({}))).await.unwrap();
|
||
let text = v["result"].to_string();
|
||
assert!(!text.contains("context.get"), "业务工具不该出现在协议层");
|
||
assert!(!text.contains("schema.table.list"));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn tools_call_returns_structured_content() {
|
||
let mut s = server();
|
||
let v = s
|
||
.handle(req(
|
||
4,
|
||
"tools/call",
|
||
json!({"name":"sspf_context","arguments":{"scope":"env"}}),
|
||
))
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(v["result"]["isError"], false);
|
||
assert_eq!(v["result"]["structuredContent"]["backend"], "native-test");
|
||
assert!(v["result"]["content"][0]["text"].is_string());
|
||
}
|
||
|
||
/// 未知工具是**协议级**错误(tool 不存在 ≠ 业务失败)。
|
||
#[tokio::test]
|
||
async fn unknown_tool_is_protocol_error() {
|
||
let mut s = server();
|
||
let v = s
|
||
.handle(req(5, "tools/call", json!({"name":"nope","arguments":{}})))
|
||
.await
|
||
.unwrap();
|
||
assert_eq!(v["error"]["code"], codes::INVALID_PARAMS);
|
||
assert!(v["error"]["message"].as_str().unwrap().contains("元工具"));
|
||
}
|
||
|
||
/// 业务失败必须是 `isError:true` 的正常返回,不是 JSON-RPC error。
|
||
#[tokio::test]
|
||
async fn business_failure_is_not_a_protocol_error() {
|
||
let mut s = server();
|
||
let v = s
|
||
.handle(req(
|
||
6,
|
||
"tools/call",
|
||
json!({"name":"sspf_call","arguments":{"tool_id":"nope"}}),
|
||
))
|
||
.await
|
||
.unwrap();
|
||
// 外层是 result(不是 error),里面 isError=false 但 payload.ok=false
|
||
assert!(v.get("result").is_some(), "业务失败不能变成协议错误");
|
||
assert_eq!(v["result"]["structuredContent"]["ok"], false);
|
||
assert_eq!(
|
||
v["result"]["structuredContent"]["error"]["code"],
|
||
"TOOL_NOT_FOUND"
|
||
);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn notifications_get_no_reply() {
|
||
let mut s = server();
|
||
let msg = Incoming {
|
||
id: None,
|
||
method: "notifications/initialized".into(),
|
||
params: Value::Null,
|
||
};
|
||
assert!(s.handle(msg).await.is_none(), "通知不该有回复");
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn unknown_method_returns_method_not_found() {
|
||
let mut s = server();
|
||
let v = s.handle(req(7, "no/such", json!({}))).await.unwrap();
|
||
assert_eq!(v["error"]["code"], codes::METHOD_NOT_FOUND);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn resources_list_and_read_work() {
|
||
let mut s = server();
|
||
let l = s.handle(req(8, "resources/list", json!({}))).await.unwrap();
|
||
assert!(!l["result"]["resources"].as_array().unwrap().is_empty());
|
||
|
||
let r = s
|
||
.handle(req(
|
||
9,
|
||
"resources/read",
|
||
json!({"uri":"sspf://registry/tools"}),
|
||
))
|
||
.await
|
||
.unwrap();
|
||
assert!(r["result"]["contents"][0]["text"]
|
||
.as_str()
|
||
.unwrap()
|
||
.contains("context.get"));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn ping_returns_empty_object() {
|
||
let mut s = server();
|
||
let v = s.handle(req(10, "ping", json!({}))).await.unwrap();
|
||
assert_eq!(v["result"], json!({}));
|
||
}
|
||
}
|