//! Studio as a Model Context Protocol server, over the protocol's Streamable HTTP transport: one
//! JSON-RPC message in, one out. Its tools answer in Markdown, as the agent endpoints do.
use std::time::Duration;
use serde_json::{Value, json};
use crate::agent::{self, WaitFor};
use crate::markdown;
use crate::queues;
use crate::store::{QueryFilter, StudioStore, TraceFilter};
use crate::workflows::{self, WorkflowFilter};
const PROTOCOL_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"];
/// Answer one JSON-RPC message of the Model Context Protocol, or a batch of them. Returns `None`
/// when the message is a notification, which gets no answer.
pub async fn handle(store: &StudioStore, payload: Value) -> Option<Value> {
if let Value::Array(messages) = payload {
let mut answers = Vec::new();
for message in messages {
if let Some(answer) = handle_message(store, message).await {
answers.push(answer);
}
}
return (!answers.is_empty()).then_some(Value::Array(answers));
}
handle_message(store, payload).await
}
async fn handle_message(store: &StudioStore, message: Value) -> Option<Value> {
let id = message.get("id").cloned().filter(|id| !id.is_null())?;
let method = message.get("method").and_then(Value::as_str).unwrap_or_default();
let params = message.get("params").cloned().unwrap_or(Value::Null);
let result = |result: Value| Some(json!({ "jsonrpc": "2.0", "id": id, "result": result }));
match method {
"initialize" => {
let requested = params
.get("protocolVersion")
.and_then(Value::as_str)
.unwrap_or_default();
let version = PROTOCOL_VERSIONS
.into_iter()
.find(|version| *version == requested)
.unwrap_or(PROTOCOL_VERSIONS[0]);
result(json!({
"protocolVersion": version,
"capabilities": { "tools": { "listChanged": false } },
"serverInfo": {
"name": "laravel-rust-studio",
"title": "Laravel Rust Studio",
"version": env!("CARGO_PKG_VERSION"),
},
"instructions": "Studio shows what this running Laravel for Rust application did, across its web server and queue workers, and acts on its workflows and jobs. Start with `studio_diagnose` to see what's wrong, with the source line of each problem. After you send the application a request, `studio_trace` with no arguments shows that request's queries, logs, and errors. `studio_wait` waits for a job, a workflow, or an email instead of sleeping. `studio_mail` returns the links and codes in the emails the application sent.",
}))
}
"ping" => result(json!({})),
"tools/list" => result(json!({ "tools": tools() })),
"tools/call" => {
let name = params.get("name").and_then(Value::as_str).unwrap_or_default();
let arguments = params.get("arguments").cloned().unwrap_or_else(|| json!({}));
let (text, is_error) = match call_tool(store, name, &arguments).await {
Ok(text) => (text, false),
Err(message) => (message, true),
};
result(json!({ "content": [{ "type": "text", "text": text }], "isError": is_error }))
}
_ => Some(json!({
"jsonrpc": "2.0",
"id": id,
"error": { "code": -32601, "message": format!("Method not found: {method}") },
})),
}
}
fn tools() -> Value {
let tool = |name: &str, description: &str, properties: Value, required: &[&str], read_only: bool| {
json!({
"name": name,
"description": description,
"inputSchema": { "type": "object", "properties": properties, "required": required },
"annotations": { "readOnlyHint": read_only, "openWorldHint": false },
})
};
let limit = json!({ "type": "integer", "description": "How many to return, at most." });
let search = json!({ "type": "string", "description": "Text to look for." });
json!([
tool(
"studio_summary",
"The application's state in one call: its health, the problems found, the latest requests, errors, workflow runs, failed jobs, and mail. Start here when you know nothing yet.",
json!({}),
&[],
true,
),
tool(
"studio_diagnose",
"Only what's wrong: errors and panics with the source line that raised them, N+1 and slow queries with the line that built them, slow requests, failed outgoing HTTP requests, failed and overdue workflow runs, and failed jobs. Each comes with a hint for fixing it, and says when it was last seen. The problems from before the server last restarted are listed apart, because the code that runs now hasn't shown them. A restart moves a problem there whether or not it was fixed, so send its request again to find out.",
json!({
"since": { "type": "number", "description": "Only the problems seen at most this many seconds ago. Use it after a change that didn't restart the server." },
}),
&[],
true,
),
tool(
"studio_trace",
"One trace in full: a request's, job's, or workflow advance's spans as a tree, with each query's SQL and the source line that built it, its cache operations, outgoing requests, logs, and errors. With no arguments, the latest HTTP request, which is what to call right after you send the application a request. A response's `X-Request-Id` header is its trace's `id`.",
json!({
"id": { "type": "string", "description": "The trace's ID. Leave it out for the latest request." },
"path": { "type": "string", "description": "With no `id`: the latest request to this path, such as `/posts`." },
"method": { "type": "string", "description": "With no `id`: the latest request with this method, such as `POST`." },
}),
&[],
true,
),
tool(
"studio_traces",
"List recent traces, newest first: HTTP requests, queued jobs, workflow advances, console commands, and scheduled tasks, each with its duration, status, and query count.",
json!({
"kind": { "type": "string", "enum": ["request", "job", "workflow", "command", "schedule"] },
"status": { "type": "string", "description": "A response status or class: `500`, `404`, `5xx`, `4xx`, `2xx`." },
"slow": { "type": "boolean", "description": "Only requests over the slow threshold." },
"errors": { "type": "boolean", "description": "Only failed traces." },
"search": search,
"limit": limit,
}),
&[],
true,
),
tool(
"studio_queries",
"List SQL queries, newest first, each with its duration, the types of its bindings, and the source line that built it.",
json!({
"trace_id": { "type": "string", "description": "Only this trace's queries." },
"slow": { "type": "boolean" },
"duplicates": { "type": "boolean", "description": "Only reads that one trace repeated: N+1 queries." },
"writes": { "type": "boolean" },
"vendor": { "type": "boolean", "description": "Also list the queries the framework and other dependencies ran themselves." },
"search": search,
"limit": limit,
}),
&[],
true,
),
tool(
"studio_exceptions",
"List the errors and panics the application reported, newest first, with their causes, the source line that raised them, and the request they happened in.",
json!({ "search": search, "limit": limit }),
&[],
true,
),
tool(
"studio_logs",
"List the application's log lines, newest first.",
json!({
"trace_id": { "type": "string", "description": "Only this trace's lines." },
"level": { "type": "string", "enum": ["error", "warn", "info", "debug"] },
"search": search,
"limit": limit,
}),
&[],
true,
),
tool(
"studio_mail",
"The emails and text messages the application sent, newest first, with their bodies and the links and codes found in them. Use it to follow a verification link, read a sign-in code, or open a workflow's approval URL.",
json!({
"to": { "type": "string", "description": "Only messages to this recipient." },
"kind": { "type": "string", "enum": ["mail", "sms"] },
"search": search,
"limit": limit,
}),
&[],
true,
),
tool(
"studio_workflows",
"List durable workflow runs, newest first, with counts by status. Each run shows its steps so far, the token it waits for, and its error.",
json!({
"status": { "type": "string", "enum": ["pending", "running", "waiting", "completed", "failed", "cancelled"] },
"workflow": { "type": "string", "description": "Only runs of the workflow with this name." },
"search": search,
"limit": limit,
}),
&[],
true,
),
tool(
"studio_workflow",
"One workflow run in full: its input, output, error, attributes, every step with its output and tries, the tokens it waits for, and the values it was resumed with.",
json!({ "id": { "type": "string", "description": "The run's ID." } }),
&["id"],
true,
),
tool(
"studio_resume_workflow",
"Give a waiting workflow run the value it waits for, as the application's own `workflow::resume` would. The value must be the JSON the workflow's `wait_for::<T>` decodes.",
json!({
"token": { "type": "string", "description": "The token the run waits for, such as `expenses.42.decision`." },
"value": { "description": "The value, as JSON." },
}),
&["token", "value"],
false,
),
tool(
"studio_retry_workflow",
"Continue a failed workflow run from the step that failed. Its earlier steps keep their recorded results.",
json!({ "id": { "type": "string", "description": "The run's ID." } }),
&["id"],
false,
),
tool(
"studio_cancel_workflow",
"Cancel a workflow run that hasn't finished.",
json!({
"id": { "type": "string", "description": "The run's ID." },
"reason": { "type": "string" },
}),
&["id"],
false,
),
tool(
"studio_queues",
"The queues: each one's depth and whether it's paused, the jobs waiting, the failed jobs with their errors and payloads, batches, and the attempts workers ran lately.",
json!({}),
&[],
true,
),
tool(
"studio_retry_failed_job",
"Put a failed job back on its queue, for a worker to run again. Fix what made it fail first: a retry runs the same job with the same data.",
json!({ "id": { "type": "string", "description": "The failed job's number, or its job ID." } }),
&["id"],
false,
),
tool(
"studio_wait",
"Wait until the application does something, and return it. Call it after you set work off, such as a request that queues a job or starts a workflow, instead of sleeping. It also returns a matching record from the last `lookback` seconds.",
json!({
"for": {
"type": "string",
"enum": ["request", "job", "workflow", "exception", "mail", "sms", "log", "activity"],
"description": "`job` and `workflow` are finished attempts and advances. `activity` is a workflow run or a job changing state, such as a run completing.",
},
"contains": { "type": "string", "description": "Words the record must contain, all of them: a path, an email address, or a run's ID and `completed`." },
"timeout": { "type": "number", "description": "Seconds to wait. 15 by default, 120 at most." },
"lookback": { "type": "number", "description": "Also accept records captured this many seconds ago. 10 by default." },
}),
&["for"],
true,
),
])
}
async fn call_tool(store: &StudioStore, name: &str, arguments: &Value) -> Result<String, String> {
let text = |key: &str| {
arguments
.get(key)
.and_then(Value::as_str)
.filter(|text| !text.is_empty())
};
let flag = |key: &str| arguments.get(key).and_then(Value::as_bool).unwrap_or(false);
let limit = |default: usize| {
arguments
.get("limit")
.and_then(Value::as_u64)
.map_or(default, |limit| (limit as usize).clamp(1, 200))
};
let required = |key: &str| text(key).ok_or_else(|| format!("the `{key}` argument is required"));
let pretty = |value: &dyn erased::Json| value.pretty();
let mount = store.config().mount_path();
match name {
"studio_summary" => Ok(markdown::render_summary_markdown(
&agent::build_agent_summary(store).await,
&mount,
)),
"studio_diagnose" => {
let within = arguments
.get("since")
.and_then(Value::as_f64)
.and_then(|seconds| Duration::try_from_secs_f64(seconds).ok());
Ok(markdown::render_diagnostics_markdown(
&agent::diagnose(store, within).await,
))
}
"studio_trace" => {
let trace = match text("id") {
Some(id) => store.get_trace(id),
None => agent::latest_request(store, text("path"), text("method")),
};
let trace = trace.ok_or("no such trace has been captured")?;
let mut out = markdown::render_trace_markdown(&trace);
markdown::append_trace_details(store, &trace, &mut out);
Ok(out)
}
"studio_traces" => {
let filter = TraceFilter {
kind: text("kind"),
status: text("status"),
search: text("search"),
slow: flag("slow"),
errors: flag("errors"),
};
let traces = store.list_traces(&filter, limit(25));
if traces.is_empty() {
return Ok("No traces match.".to_owned());
}
Ok(traces.iter().map(markdown::trace_line).collect::<Vec<_>>().join("\n"))
}
"studio_queries" => {
let filter = QueryFilter {
trace_id: text("trace_id"),
slow: flag("slow"),
writes: flag("writes"),
duplicates: flag("duplicates"),
app_only: !flag("vendor"),
search: text("search"),
};
Ok(pretty(&store.list_queries(&filter, limit(40))))
}
"studio_exceptions" => {
let exceptions = store.list_exceptions(text("search"), limit(10));
if exceptions.is_empty() {
return Ok("No errors have been captured.".to_owned());
}
Ok(exceptions
.iter()
.map(|exception| markdown::render_exception_markdown(exception, &mount))
.collect::<Vec<_>>()
.join("\n---\n\n"))
}
"studio_logs" => Ok(pretty(&store.list_logs(
text("trace_id"),
text("level"),
text("search"),
limit(50),
))),
"studio_mail" => {
let mails = store.list_mails(text("kind"), text("to").or(text("search")), limit(5));
if mails.is_empty() {
return Ok("No mail has been captured.".to_owned());
}
Ok(mails
.iter()
.map(markdown::render_mail_markdown)
.collect::<Vec<_>>()
.join("\n---\n\n"))
}
"studio_workflows" => {
let filter = WorkflowFilter {
status: text("status").map(str::to_owned),
workflow: text("workflow").map(str::to_owned),
attribute: None,
search: text("search").map(str::to_owned),
limit: limit(30),
};
Ok(pretty(&workflows::list_workflows(store, filter).await))
}
"studio_workflow" => {
let id = required("id")?;
let run = workflows::get_workflow(id)
.await
.map_err(|error| error.to_string())?
.ok_or_else(|| format!("no workflow run has the ID `{id}`"))?;
Ok(markdown::render_workflow_markdown(&run))
}
"studio_resume_workflow" => {
let token = required("token")?.to_owned();
let value = arguments.get("value").cloned().unwrap_or(Value::Null);
let outcome = workflows::resume_workflow(token, value)
.await
.map_err(|error| error.to_string())?;
if outcome.ok {
Ok(outcome.message)
} else {
Err(outcome.message)
}
}
"studio_retry_workflow" => {
let outcome = workflows::retry_workflow(required("id")?)
.await
.map_err(|error| error.to_string())?;
if outcome.ok {
Ok(outcome.message)
} else {
Err(outcome.message)
}
}
"studio_cancel_workflow" => {
let outcome = workflows::cancel_workflow(required("id")?, text("reason").map(str::to_owned))
.await
.map_err(|error| error.to_string())?;
if outcome.ok {
Ok(outcome.message)
} else {
Err(outcome.message)
}
}
"studio_queues" => Ok(pretty(&queues::queue_overview(store).await)),
"studio_retry_failed_job" => {
let outcome = queues::retry_failed_job(required("id")?)
.await
.map_err(|error| error.to_string())?;
if outcome.ok {
Ok(outcome.message)
} else {
Err(outcome.message)
}
}
"studio_wait" => {
let seconds = |key: &str, default: f64| arguments.get(key).and_then(Value::as_f64).unwrap_or(default);
let wait = WaitFor {
kind: required("for")?.to_owned(),
contains: text("contains").map(str::to_owned),
timeout: Duration::from_secs_f64(seconds("timeout", 15.0).clamp(0.0, 120.0)),
lookback: Duration::from_secs_f64(seconds("lookback", 10.0).clamp(0.0, 3600.0)),
};
match agent::wait_for_event(store, wait).await {
Some(event) => Ok(pretty(&event)),
None => Err("nothing matching was captured before the timeout".to_owned()),
}
}
_ => Err(format!("unknown tool `{name}`")),
}
}
/// Lets one closure pretty-print values of different types.
mod erased {
pub(super) trait Json {
fn pretty(&self) -> String;
}
impl<T: serde::Serialize> Json for T {
fn pretty(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_else(|error| format!("{{\"error\": \"{error}\"}}"))
}
}
}