laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! 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}\"}}"))
        }
    }
}