构建

会拒绝的工具 — 模式是约定,不是保证

作者: makemind · 2026年2月20日

第二篇的工具不收参数。这次收。而且 不信任收到的东西。

模式

inputSchema: const {
  'type': 'object',
  'properties': {
    'count': {'type': 'integer', 'description': 'How many to admit, 1 or more'},
  },
  'required': ['count'],
},

加上它,调用方就知道该送什么。模型会照着它凑参数。

可是模式不是保证

写了 'type': 'integer' 并不会让整数真的到来。模式是 给调用方的指引,对方可能不遵守,也可能做不到。

所以处理器再看一遍。

handler: (args) async {
  final n = args['count'];
  // The schema says integer; the caller may still send anything.
  if (n is! int || n < 1) {
    return CallToolResult(
      content: [TextContent(text: 'desk.admit: count must be 1 or more')],
      isError: true,
    );
  }
  // And the desk cannot admit people who are not there.
  if (n > waiting) {
    return CallToolResult(
      content: [TextContent(text: 'only $waiting waiting')],
      isError: true,
    );
  }
  waiting -= n;
  return CallToolResult(
    content: [TextContent(text: jsonEncode({'waiting': waiting}))],
  );
},

两种拒绝性质不同

有两道检查,理由不一样。

n < 1 — 值本身就说不通。放 0 个人进来永远是错的。这是输入的问题。

n > waiting — 值没毛病,但眼下不可能。3 个人在等,放不出 99 个。可要是有 100 个在等,99 就正常。这是状态的问题。

之所以要分开,是因为消息不同。

count must be 1 or more     ← 再送一次还是错
only 3 waiting              ← 送 3 以内就行

一律用 isError: true 糊过去,调用方就不知道该重试还是该放弃。

此内容需要开发者或更高等级

登录并升级您的方案即可继续阅读。

查看方案
Twitter