handle method
Handles one JSON-RPC message: answers a request, or null for a notification.
Implementation
Future<Map<String, Object?>?> handle(Map<String, Object?> message) async {
final id = message['id'];
final method = message['method'];
final isNotification = !message.containsKey('id');
Map<String, Object?> result(Object? value) => {
'jsonrpc': '2.0',
'id': id,
'result': value,
};
Map<String, Object?> error(int code, String text) => {
'jsonrpc': '2.0',
'id': id,
'error': {'code': code, 'message': text},
};
if (message['jsonrpc'] != '2.0' || method is! String) {
return isNotification ? null : error(-32600, 'Invalid request.');
}
if (isNotification) return null;
final params = message['params'];
switch (method) {
case 'initialize':
return result({
'protocolVersion': protocolVersion,
'capabilities': {
'tools': {'listChanged': false},
},
'serverInfo': {'name': serverName, 'version': '1'},
});
case 'ping':
return result(const <String, Object?>{});
case 'tools/list':
return result({
'tools': [
for (final tool in binding.registry.tools) tool.toJsonSchema(),
],
});
case 'tools/call':
if (params is! Map || params['name'] is! String) {
return error(-32602, 'tools/call needs a "name".');
}
final arguments = params['arguments'] ?? const <String, Object?>{};
if (arguments is! Map) {
return error(-32602, '"arguments" must be an object.');
}
final answer = await binding._dispatch(
params['name']! as String,
arguments.cast<String, Object?>(),
AgentAuditEntryPoint.mcp,
);
return result({
'content': [
{'type': 'text', 'text': answer.toText()},
],
'isError': answer.isError,
});
default:
return error(-32601, 'Method not found: $method');
}
}