Skip to content
Back to search

MCP-Mastra

Express 5 MCP server plus agent loop with step limits and deadlines, viewed through a Next.js 15 tool trace

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dev-genius-ai--mcp-mastra/badge.svg)](/listings/dev-genius-ai--mcp-mastra)

HTML

<a href="/listings/dev-genius-ai--mcp-mastra"><img src="/api/listings/dev-genius-ai--mcp-mastra/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

With Docker:

docker compose up --build

Then open http://localhost:7272. The API is on http://localhost:7271. Every setting has a default; to change one, copy `.env.example` to `.env` next to `docker-compose.yml` and edit it.

Without Docker (Node 22, see `.nvmrc`), in two terminals:

cd Backend
cp .env.example .env   # optional
npm install
npm run dev            # API on http://localhost:7271
cd Frontend
npm install
npm run dev            # console on http://localhost:7272

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 212 lines
  1. # MCP-Mastra
  2. A small Model Context Protocol server, an agent loop that reaches its tools through an MCP client, and a Next.js console that shows the answer next to every tool call the agent made: which tool, with which arguments, why, and what came back.
  3. ![Agent console: the answer on the left, the numbered tool trace on the right](docs/screenshots/agent-console.png)
  4. The point is to make tool selection visible. When an agent picks the wrong tool or sends bad arguments, the trace shows it instead of leaving you to guess from the final answer.
  5. By default the agent runs on a deterministic local stub (a keyword rule table), so the whole stack works with no API key and no network. Setting `MODEL_PROVIDER=openai` swaps in a Mastra agent on an OpenAI model behind the same interface.
  6. ## What's in it
  7. - An MCP server with `initialize`, `ping`, `tools/list` and `tools/call`, served over HTTP (`POST /mcp`) and over stdio.
  8. - Three tools: `get_context` and `list_context_sections` search a small ad-copy playbook; `get_weather` returns a synthetic reading derived from the city and date (deterministic, not a real forecast).
  9. - An agent loop that discovers tools over MCP, validates arguments with Zod, stops after `MAX_TOOL_STEPS`, and has deadlines on each tool call and on the whole run.
  10. - A web console with the agent chat and a tool catalogue page that sends raw `tools/call` requests to `/mcp`.
  11. Backend: Node 22, TypeScript, Express 5, Zod, `@mastra/core`. Frontend: Next.js 15, React 19, Tailwind 4.
  12. ## Quick start
  13. With Docker:
  14. ```bash
  15. docker compose up --build
  16. ```
  17. Then open http://localhost:7272. The API is on http://localhost:7271. Every setting has a default; to change one, copy `.env.example` to `.env` next to `docker-compose.yml` and edit it.
  18. Without Docker (Node 22, see `.nvmrc`), in two terminals:
  19. ```bash
  20. cd Backend
  21. cp .env.example .env # optional
  22. npm install
  23. npm run dev # API on http://localhost:7271
  24. ```
  25. ```bash
  26. cd Frontend
  27. npm install
  28. npm run dev # console on http://localhost:7272
  29. ```
  30. ## How it fits together
  31. ```mermaid
  32. flowchart LR
  33. UI["Next.js console<br/>:7272"] -- "POST /api/chat" --> API["Express API<br/>:7271"]
  34. UI -- "POST /mcp (tools/call)" --> API
  35. API --> Runner["AgentRunner<br/>step cap, run deadline"]
  36. Runner -- "decide()" --> Provider{{"ModelProvider<br/>stub or Mastra/OpenAI"}}
  37. Runner --> Client["McpClient"]
  38. Client -- "in-memory transport" --> Server["McpServer"]
  39. API -- "/mcp" --> Server
  40. Stdio["stdio transport"] --> Server
  41. Server --> Registry["ToolRegistry<br/>Zod validation, per-call deadline"]
  42. Registry --> Tools["get_context<br/>list_context_sections<br/>get_weather"]
  43. ```
  44. The API holds one `McpServer` instance. The agent reaches it through the same `McpClient` an external consumer would use, over an in-memory transport, so the API has no back door into the tools. `/mcp` and the stdio entry point serve that same server to outside clients.
  45. ## API
  46. | Method | Path | Description |
  47. |---|---|---|
  48. | GET | `/healthz` | Provider, protocol version, tool names, limits, config warnings |
  49. | GET | `/api/tools` | Tool catalogue fetched through the MCP client |
  50. | POST | `/api/chat` | `{ "question": "..." }` in, the answer and the step trace out |
  51. | POST | `/mcp` | Raw JSON-RPC 2.0 |
  52. These exchanges were captured from the Compose stack.
  53. Ask the agent:
  54. ```bash
  55. curl -s -X POST http://localhost:7271/api/chat \
  56. -H 'Content-Type: application/json' \
  57. -d '{"question":"What is the weather in Lisbon?"}'
  58. ```
  59. ```json
  60. {
  61. "question": "What is the weather in Lisbon?",
  62. "answer": "Here is what the get_weather tool returned for \"What is the weather in Lisbon?\":\n\nLisbon on 2026-11-08: heavy rain. Temperature -3 C, wind 25 kph, humidity 87%. (Synthetic reading - deterministic from city and date, not a live forecast.)",
  63. "provider": "stub",
  64. "providerLabel": "Deterministic local stub",
  65. "toolsDiscovered": ["get_context", "get_weather", "list_context_sections"],
  66. "steps": [
  67. {
  68. "index": 0,
  69. "tool": "get_weather",
  70. "arguments": { "city": "Lisbon" },
  71. "rationale": "The question asks about weather and names a place.",
  72. "ok": true,
  73. "output": "Lisbon on 2026-11-08: heavy rain. Temperature -3 C, wind 25 kph, humidity 87%. (Synthetic reading - deterministic from city and date, not a live forecast.)",
  74. "structured": {
  75. "city": "Lisbon", "date": "2026-11-08", "condition": "heavy rain",
  76. "temperatureC": -3, "windKph": 25, "humidityPct": 87, "synthetic": true
  77. },
  78. "durationMs": 1
  79. }
  80. ],
  81. "stoppedBy": "final",
  82. "durationMs": 3
  83. }
  84. ```
  85. `stoppedBy` is `final` when the provider answered, `step_limit` when it hit `MAX_TOOL_STEPS`, `deadline` when the run went over `RUN_TIMEOUT_MS`, and `cancelled` when the client went away first.
  86. Call a tool directly over JSON-RPC:
  87. ```bash
  88. curl -s -X POST http://localhost:7271/mcp \
  89. -H 'Content-Type: application/json' \
  90. -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_weather","arguments":{"city":"Lisbon","date":"2026-03-14"}}}'
  91. ```
  92. ```json
  93. {
  94. "jsonrpc": "2.0",
  95. "id": 2,
  96. "result": {
  97. "content": [
  98. {
  99. "type": "text",
  100. "text": "Lisbon on 2026-03-14: clear. Temperature -1 C, wind 13 kph, humidity 72%. (Synthetic reading - deterministic from city and date, not a live forecast.)"
  101. }
  102. ],
  103. "structuredContent": {
  104. "city": "Lisbon", "date": "2026-03-14", "condition": "clear",
  105. "temperatureC": -1, "windKph": 13, "humidityPct": 72, "synthetic": true
  106. }
  107. }
  108. }
  109. ```
  110. Bad arguments are a protocol error with the failing field named:
  111. ```json
  112. {"jsonrpc":"2.0","id":3,"error":{"code":-32602,"message":"Invalid arguments for tool \"get_weather\"","data":[{"path":"city","message":"String must contain at least 1 character(s)"}]}}
  113. ```
  114. A body that is not JSON gets HTTP 400 with a JSON-RPC parse error, `{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"Parse error"}}`, and a body over 64 kB gets 413.
  115. ![Tool catalogue sending a raw tools/call](docs/screenshots/tool-call.png)
  116. ## Running as a stdio MCP server
  117. Desktop MCP clients launch servers as a subprocess and speak newline-delimited JSON over stdin/stdout. The same tools are available that way:
  118. ```bash
  119. cd Backend && npm run mcp:stdio # from source, via ts-node
  120. node dist/stdio.js # after npm run build, or inside the backend image
  121. ```
  122. ```text
  123. > {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}
  124. < {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{"tools":{"listChanged":false}},"serverInfo":{"name":"mcp-mastra-tools","version":"1.0.0"}}}
  125. ```
  126. Diagnostics go to stderr, so nothing but protocol ever reaches stdout.
  127. ## Configuration
  128. Backend variables (see `Backend/.env.example`; Compose passes the same names through from `.env`):
  129. | Variable | Default | Meaning |
  130. |---|---|---|
  131. | `PORT`, `HOST` | `7271`, `0.0.0.0` | Where the API listens |
  132. | `MODEL_PROVIDER` | `stub` | `stub` or `openai` |
  133. | `OPENAI_API_KEY`, `OPENAI_MODEL` | unset, `gpt-4o-mini` | Only read when the provider is `openai` |
  134. | `MAX_TOOL_STEPS` | `4` | Ceiling on tool calls per question |
  135. | `TOOL_TIMEOUT_MS` | `5000` | Deadline for one `tools/call`, on every transport |
  136. | `RUN_TIMEOUT_MS` | `60000` | Deadline for a whole `/api/chat` run, model calls included |
  137. | `CORS_ORIGINS` | `*` | Comma-separated allow-list |
  138. The frontend reads `NEXT_PUBLIC_API_BASE` (default `http://localhost:7271`). It is inlined at build time, so in Docker it is a build argument.
  139. With `MODEL_PROVIDER=openai` and no key, the server logs a warning, reports it on `/healthz`, and falls back to the stub rather than failing.
  140. ## Design notes
  141. - **One seam for models.** `ModelProvider` has a single `decide()` method: given the transcript and the discovered tools, call a tool or answer. The loop owns everything else (the step cap, the MCP calls, the trace, the deadlines), so the stub and the OpenAI provider behave identically from the console's point of view. The OpenAI provider asks the model for one JSON decision at a time instead of handing tool execution to the framework, which keeps the trace and the step cap in this project's hands.
  142. - **Protocol errors and tool errors stay apart.** An unknown tool or invalid arguments raises a JSON-RPC error. A tool that throws, or runs past `TOOL_TIMEOUT_MS`, returns content with `isError: true`, which the agent reads as a result and can recover from.
  143. - **Deadlines and cancellation.** Every tool handler gets an `AbortSignal` that fires at its deadline. The run has its own deadline, and `/api/chat` aborts the run when the client disconnects, so an abandoned request does not keep paying for model calls. The signal is passed to the model call, and the loop also stops waiting on its own.
  144. - **The stub is the default, not a fallback.** It routes weather questions (matched as whole words) to `get_weather`, catalogue questions to `list_context_sections`, and everything else to `get_context`. That is enough to exercise discovery, validation, the trace and the UI with stable test assertions.
  145. - **The weather tool is synthetic on purpose.** A reading hashed from city and date is varied and reproducible, so a test can tell whether the arguments arrived.
  146. - **Lazy model imports.** `@mastra/core` and `@ai-sdk/openai` are imported only when the OpenAI provider makes its first call, so the default path never loads them.
  147. ## Tests and checks
  148. ```bash
  149. cd Backend && npm test && npm run lint && npm run typecheck && npm run format:check
  150. cd Frontend && npm test && npm run lint && npm run typecheck && npm run build
  151. ```
  152. The backend has 110 Vitest tests covering the protocol, server, client, registry deadlines, tools, the stub, the loop (step cap, run deadline, cancellation) and the HTTP API, including a real client disconnect. The frontend has 14 tests for the API client and formatting helpers.
  153. ![Agent console on a phone](docs/screenshots/agent-console-mobile.png)
  154. ## Limitations
  155. - The MCP surface covers tools only: no resources, prompts, sampling, or `notifications/cancelled` from the client side.
  156. - `/mcp` has no authentication. Do not expose it beyond a trusted network.
  157. - The OpenAI path type-checks and its JSON parsing is tested, but it has not been run against a real key. `@mastra/core` stays on 0.18 and `@ai-sdk/openai` on 1.x; moving to Mastra 1.x and AI SDK v5 is a migration that needs a key to verify.
  158. - The stub answers with one tool call per question and does not chain tools.
  159. - The tool catalogue page only renders inputs for string arguments; `get_context`'s numeric `limit` can be sent through `/mcp` directly.
  160. ## License
  161. MIT, see [LICENSE](LICENSE).

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.