use crate::Result;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;
pub type McpToolFn = Arc<dyn Fn(Value) -> Result<Value> + Send + Sync>;
#[derive(Clone)]
pub struct McpTool {
pub name: String,
pub description: String,
pub input_schema: Value,
pub handler: McpToolFn,
}
impl std::fmt::Debug for McpTool {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpTool")
.field("name", &self.name)
.field("description", &self.description)
.field("input_schema", &self.input_schema)
.finish()
}
}
impl McpTool {
pub fn new(
name: impl Into<String>,
description: impl Into<String>,
input_schema: Value,
handler: impl Fn(Value) -> Result<Value> + Send + Sync + 'static,
) -> Self {
Self {
name: name.into(),
description: description.into(),
input_schema,
handler: Arc::new(handler),
}
}
pub fn to_mcp_json(&self) -> Value {
json!({
"name": self.name,
"description": self.description,
"inputSchema": self.input_schema,
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct McpResource {
pub uri: String,
pub name: String,
pub description: Option<String>,
pub mime_type: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpRpcRequest {
#[serde(default = "default_jsonrpc_version")]
pub jsonrpc: String,
pub id: Option<Value>,
pub method: String,
#[serde(default)]
pub params: Option<Value>,
}
fn default_jsonrpc_version() -> String {
"2.0".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpRpcResponse {
pub jsonrpc: String,
pub id: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<McpRpcError>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpRpcError {
pub code: i32,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl McpRpcResponse {
pub fn success(id: Option<Value>, result: Value) -> Self {
Self {
jsonrpc: "2.0".to_string(),
id,
result: Some(result),
error: None,
}
}
pub fn error(
id: Option<Value>,
code: i32,
message: impl Into<String>,
data: Option<Value>,
) -> Self {
Self {
jsonrpc: "2.0".to_string(),
id,
result: None,
error: Some(McpRpcError {
code,
message: message.into(),
data,
}),
}
}
}
pub fn handle_mcp_request(
req: McpRpcRequest,
app_title: &str,
tools: &[McpTool],
) -> McpRpcResponse {
let id = req.id.clone();
match req.method.as_str() {
"initialize" => McpRpcResponse::success(
id,
json!({
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": { "listChanged": false },
"resources": { "subscribe": false, "listChanged": false },
"logging": {}
},
"serverInfo": {
"name": format!("grio-mcp-{app_title}"),
"version": "0.1.0",
}
}),
),
"notifications/initialized" => McpRpcResponse::success(id, json!({ "status": "ok" })),
"ping" => McpRpcResponse::success(id, json!({})),
"tools/list" => {
let tools_json: Vec<Value> = tools.iter().map(|t| t.to_mcp_json()).collect();
McpRpcResponse::success(
id,
json!({
"tools": tools_json
}),
)
}
"tools/call" => {
let Some(params) = req.params else {
return McpRpcResponse::error(id, -32602, "Missing params for tools/call", None);
};
let tool_name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
let arguments = params.get("arguments").cloned().unwrap_or(json!({}));
let Some(tool) = tools.iter().find(|t| t.name == tool_name) else {
return McpRpcResponse::error(
id,
-32601,
format!("Tool not found: '{tool_name}'"),
None,
);
};
match (tool.handler)(arguments) {
Ok(output) => {
let text = if let Value::String(s) = output {
s
} else {
output.to_string()
};
McpRpcResponse::success(
id,
json!({
"content": [
{
"type": "text",
"text": text
}
],
"isError": false
}),
)
}
Err(e) => McpRpcResponse::success(
id,
json!({
"content": [
{
"type": "text",
"text": format!("Error executing tool '{tool_name}': {e}")
}
],
"isError": true
}),
),
}
}
"resources/list" => McpRpcResponse::success(
id,
json!({
"resources": [
{
"uri": "grio://app/manifest",
"name": "Application Manifest",
"description": "grio active component tree and API schema",
"mimeType": "application/json"
}
]
}),
),
other => McpRpcResponse::error(
id,
-32601,
format!("Method not found or unsupported: '{other}'"),
None,
),
}
}