@agentailor/create-mcp-server 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +27 -3
  2. package/dist/assets/skills/tool-design/SKILL.md +107 -0
  3. package/dist/assets/skills/tool-design/references/examples.md +273 -0
  4. package/dist/assets/skills/tool-design/references/principles.md +261 -0
  5. package/dist/assets/skills/tool-design/references/testing.md +195 -0
  6. package/dist/cli.d.ts +1 -0
  7. package/dist/cli.js +4 -2
  8. package/dist/cli.test.js +19 -0
  9. package/dist/index.js +1 -0
  10. package/dist/interactive.js +8 -0
  11. package/dist/project-generator.d.ts +1 -0
  12. package/dist/project-generator.js +27 -4
  13. package/dist/skills.d.ts +43 -0
  14. package/dist/skills.js +64 -0
  15. package/dist/skills.test.d.ts +1 -0
  16. package/dist/skills.test.js +85 -0
  17. package/dist/templates/common/agents.md.d.ts +9 -0
  18. package/dist/templates/common/agents.md.js +221 -0
  19. package/dist/templates/common/agents.md.test.d.ts +1 -0
  20. package/dist/templates/common/agents.md.test.js +142 -0
  21. package/dist/templates/common/package.json.js +19 -8
  22. package/dist/templates/common/tsconfig.json.d.ts +3 -1
  23. package/dist/templates/common/tsconfig.json.js +8 -2
  24. package/dist/templates/fastmcp/index.js +5 -3
  25. package/dist/templates/fastmcp/readme.js +13 -0
  26. package/dist/templates/sdk/stateful/auth.js +5 -1
  27. package/dist/templates/sdk/stateful/auth.test.js +6 -2
  28. package/dist/templates/sdk/stateful/index.d.ts +6 -0
  29. package/dist/templates/sdk/stateful/index.js +7 -1
  30. package/dist/templates/sdk/stateful/readme.js +1 -1
  31. package/dist/templates/sdk/stateful/templates.test.js +6 -7
  32. package/dist/templates/sdk/stateless/index.d.ts +6 -0
  33. package/dist/templates/sdk/stateless/index.js +10 -1
  34. package/dist/templates/sdk/stateless/prompts.d.ts +1 -0
  35. package/dist/templates/sdk/stateless/prompts.js +32 -0
  36. package/dist/templates/sdk/stateless/readme.js +72 -13
  37. package/dist/templates/sdk/stateless/resources.d.ts +1 -0
  38. package/dist/templates/sdk/stateless/resources.js +49 -0
  39. package/dist/templates/sdk/stateless/server-test.d.ts +1 -0
  40. package/dist/templates/sdk/stateless/server-test.js +175 -0
  41. package/dist/templates/sdk/stateless/server.js +14 -68
  42. package/dist/templates/sdk/stateless/store-test.d.ts +1 -0
  43. package/dist/templates/sdk/stateless/store-test.js +38 -0
  44. package/dist/templates/sdk/stateless/store.d.ts +1 -0
  45. package/dist/templates/sdk/stateless/store.js +107 -0
  46. package/dist/templates/sdk/stateless/templates.test.js +160 -14
  47. package/dist/templates/sdk/stateless/tools.d.ts +1 -0
  48. package/dist/templates/sdk/stateless/tools.js +172 -0
  49. package/dist/templates/sdk/stdio/index.d.ts +6 -0
  50. package/dist/templates/sdk/stdio/index.js +6 -0
  51. package/dist/templates/sdk/stdio/readme.js +64 -11
  52. package/dist/templates/sdk/stdio/templates.test.js +11 -13
  53. package/package.json +2 -2
package/README.md CHANGED
@@ -34,6 +34,7 @@ npx @agentailor/create-mcp-server --name=my-server
34
34
  | `--template` | `-t` | `stateless` | Accepted for compatibility; SDK v2 serves both modes through one per-request idiom |
35
35
  | `--oauth` | — | `false` | Enable OAuth (sdk HTTP only, incompatible with --stdio) |
36
36
  | `--no-git` | — | `false` | Skip git initialization |
37
+ | `--no-skills` | — | `false` | Skip adding the tool-design skill |
37
38
  | `--help` | `-h` | — | Show help |
38
39
  | `--version` | `-V` | — | Show version |
39
40
 
@@ -134,19 +135,42 @@ SDK v2 serves every HTTP request through a single per-request idiom: `createMcpH
134
135
  ```
135
136
  my-mcp-server/
136
137
  ├── src/
137
- │ ├── server.ts # MCP server (tools, prompts, resources)
138
- │ ├── index.ts # Express app and transport setup
139
- │ └── auth.ts # OAuth middleware (if enabled)
138
+ │ ├── server.ts # Creates the server, registers the primitives
139
+ │ ├── tools.ts # Tool definitions
140
+ │ ├── prompts.ts # Prompt definitions
141
+ │ ├── resources.ts # Resource definitions
142
+ │ ├── notes-store.ts # Example data layer (no MCP imports)
143
+ │ ├── notes-store.test.ts # Store unit tests
144
+ │ ├── server.test.ts # Tests driven through a real MCP client
145
+ │ ├── index.ts # Express app and transport setup
146
+ │ └── auth.ts # OAuth middleware (if enabled)
140
147
  ├── Dockerfile # Production-ready Docker build
141
148
  ├── package.json
142
149
  ├── tsconfig.json
143
150
  ├── .gitignore
144
151
  ├── .env.example
152
+ ├── AGENTS.md # Working notes for humans and coding agents
145
153
  └── README.md
146
154
  ```
147
155
 
156
+ SDK projects come with a worked example — a small notes server — and a test suite
157
+ that runs green immediately, so there is a working pattern to copy when you add
158
+ your own tools. FastMCP projects ship the example only, without tests, for now.
159
+
160
+ Projects also get Agentailor's [tool-design](https://github.com/agentailor/skills)
161
+ skill at `.agents/skills/`, so a coding agent working in the project has the
162
+ guidance on hand. It is bundled with the CLI, so this needs no network and adds
163
+ nothing to scaffolding time. Pass `--no-skills` to skip it, and run
164
+ `npx skills update -p -y` inside the project if you want a newer version.
165
+
166
+ Every project also gets an `AGENTS.md` covering the things that are easy to get
167
+ wrong: how to write a tool an agent can use, how to organize tools as they grow,
168
+ and the transport-specific traps (state is per-request over HTTP; stdout belongs
169
+ to the protocol over stdio).
170
+
148
171
  **Scripts:**
149
172
  - `npm run dev` — build and start the server
173
+ - `npm test` — run the test suite (SDK projects)
150
174
  - `npm run inspect` — open MCP Inspector (update URL in `package.json` if needed)
151
175
 
152
176
  ## Learning Resources
@@ -0,0 +1,107 @@
1
+ ---
2
+ name: tool-design
3
+ description: Design and verify tools that AI agents can actually use — for any framework or language (MCP servers, LangChain/LangGraph, function-calling, raw JSON schema; TypeScript, Python, or otherwise). Use when writing a new tool for an agent, reviewing or fixing an existing tool definition, deciding how to split capabilities into tools, writing tests or evals for a tool, checking that a tool's output matches what its description promised, or debugging why an agent misuses, mis-selects, misreads the output of, or floods its context with a tool. Applies equally to standalone tools and MCP-server tools — a tool is a tool.
4
+ ---
5
+
6
+ # Tool Design
7
+
8
+ ## Overview
9
+
10
+ A tool is a **contract between a deterministic system and a non-deterministic caller.** A normal API assumes a rational developer who reads the docs, handles error codes, and knows which endpoint to call. An agent breaks all of those assumptions: it may pick the wrong tool because two names look alike, pass malformed parameters despite a clear schema, pull back a dataset that blows its own context window, or misread a cryptic error and retry the same failing call.
11
+
12
+ So tools for agents are designed **defensively**: clear enough that the agent can't easily misuse them, informative enough to steer the agent toward a better next move, and lean enough to spend the context window carefully.
13
+
14
+ The payoff: **agent and human ergonomics align.** A tool that an agent uses well is almost always a tool a human finds intuitive too. Designing for a non-deterministic caller just produces a better API.
15
+
16
+ **None of this is framework- or language-specific.** The same five principles apply whether the tool is an MCP server tool, a LangChain/LangGraph tool, an OpenAI/Anthropic function-calling definition, or a plain function exposed to a model — and whether it's written in TypeScript, Python, or anything else. What varies is the syntax of `name` / `description` / `parameters` / `returns`; the design thinking does not. See [references/examples.md](references/examples.md) for the *same* tool proven across languages and surfaces.
17
+
18
+ ## The Five Principles
19
+
20
+ Apply these when writing or reviewing any tool. The deep dive with worked schema shapes is in [references/principles.md](references/principles.md).
21
+
22
+ ### 1. Strategic selection
23
+
24
+ Build tools around **user workflows, not database schemas or API endpoints.** Don't wrap every endpoint as its own tool — the agent then struggles to choose among near-duplicates and you spend prompt budget documenting all of them. Consolidate related operations into one well-parameterized tool when it maps to how a user thinks about the task.
25
+
26
+ > Prefer one `get_expenses(start_date, end_date, category?, ...)` over `get_expense_by_id` + `list_all_expenses` + `filter_by_category` + `search_expenses`.
27
+
28
+ Ask: does this map to how users think about the task? Would merging it with a sibling reduce the number of decisions the agent has to make?
29
+
30
+ **But don't consolidate on data alone.** Two tools touching the same table can still be two workflows. A bounded row listing ("show me my Dining transactions in June") and an aggregate query ("how much did I spend on Dining last quarter") look like prime merge candidates — same data, adjacent phrasing. Merging them into one tool with a mode flag satisfies the principle's letter and makes selection *harder*: the agent now reasons about which mode on every call, and the two have genuinely different return shapes and safety properties. Consolidate operations that share a **workflow**, not operations that merely share **data**.
31
+
32
+ ### 2. Clear naming and namespacing
33
+
34
+ Names and descriptions decide whether the agent picks the right tool. Use descriptive, action-oriented names — never bare `search`, `fetch`, `process`. When an agent has tools from several sources, collisions cause mis-selection, so **namespace with a consistent prefix** — by service (`slack_search`, `notion_search`) or resource (`expenses_get`, `expenses_summarize`).
35
+
36
+ > Check whether your surface prefixes for you: many MCP clients auto-prepend the server name, so hardcoding the prefix too yields `agentailor_agentailor_search`. Let the surface prefix, or prefix yourself — not both. See [references/principles.md](references/principles.md#2-clear-naming-and-namespacing).
37
+
38
+ A description should answer three questions:
39
+ - **What** does it do? (1–2 sentences)
40
+ - **When** should the agent reach for it? (a few example queries)
41
+ - **How** is it used? (key parameters, constraints, what it returns)
42
+
43
+ Every parameter gets a description with its **format, an example, and constraints** — `"Start date in ISO format (YYYY-MM-DD). Example: '2025-01-01'"`, not `start_date: string`.
44
+
45
+ ### 3. Meaningful context return
46
+
47
+ Return information the agent can **reason about directly**, not identifiers it must resolve with another call. Include the expense's description and category, not just a UUID. Attach lightweight metadata (totals, the date range, which filters were applied) so the agent knows what it's looking at.
48
+
49
+ Make verbosity **configurable**: a `response_format` of `concise` (essential fields) vs `detailed` (full metadata) lets the agent trade detail against tokens per task. When a result feeds the next tool call, return the exact value that next call needs (e.g. the canonical URL/id to pass along), so the agent can chain without a lookup.
50
+
51
+ ### 4. Token efficiency
52
+
53
+ Every token in a tool response is a token unavailable for reasoning. Give collection-returning tools **sensible default limits** (e.g. 50) plus pagination and filter parameters. When you truncate, **say so and say how to continue** — "Found 847, returning 50; narrow the date range or add a category filter" beats silently dropping rows. Validate inputs that would produce huge responses (e.g. reject a >1-year range) *before* running the query.
54
+
55
+ ### 5. Descriptions are prompts
56
+
57
+ The tool's name, description, and parameter docs **are prompt engineering** — every word shapes how the agent uses the tool. Be explicit about when to use it, required vs optional parameters, and the shape of the output. Refine this text iteratively against real agent behavior: unclear wording is the most common reason an agent mis-selects or mis-calls a tool.
58
+
59
+ ## Validation Checklist
60
+
61
+ When writing or reviewing a tool, confirm:
62
+
63
+ - [ ] **Strategic** — consolidates a real workflow; not one-tool-per-endpoint, not overlapping near-duplicates.
64
+ - [ ] **Named** — descriptive, action-oriented, namespaced to avoid collisions; not a bare verb.
65
+ - [ ] **Described** — the description says what / when / how, with example queries.
66
+ - [ ] **Parameterized** — every parameter documents format + example + constraints; required vs optional is intentional; optionals have sensible defaults.
67
+ - [ ] **Contextual** — returns human-readable info and metadata, not just IDs; verbosity is configurable when responses can be large.
68
+ - [ ] **Efficient** — default limits, pagination/filters, truncation messages that guide the next query; guards against responses that would blow the context window.
69
+ - [ ] **Helpful on failure** — errors explain what went wrong and what to do next, with an example; no cryptic codes.
70
+ - [ ] **Tested** — the checklist items above that are mechanically checkable have deterministic tests (unit at minimum, integration where real I/O decides correctness); the behaviors only a model can exercise have evals (or are knowingly deferred).
71
+
72
+ ## Testing
73
+
74
+ The checklist above says what a good tool does. Nothing so far says how you know it still does — and **a tool description is a contract with a non-deterministic caller, so an unverified contract is the default failure.** The implementation drifts from what the description promised, and the agent, which has no way to check, believes the description.
75
+
76
+ Two layers, split on whether a model is in the loop, and neither subsumes the other:
77
+
78
+ **Deterministic tests — cheap, repeatable, always.** Whatever runs without a model and gives a stable verdict: unit tests as the floor, plus integration tests when correctness depends on real I/O (a multi-step write, a transaction boundary, a third-party API). Most of the checklist is mechanically testable this way: that truncation is *signalled* rather than merely applied, that errors return structured actionable objects, that the payload really contains the fields the description promised, that defaults behave as documented. Assert on the **tool's returned payload** — the surface the agent sees, and the same surface an eval grades later, so the assertions survive.
79
+
80
+ > A tool that silently caps rows at 50 while its description promises a bounded list will report 262 matches as `count: 50`. A test that stubs a full page against a larger total and asserts `truncated === true` catches that in milliseconds. See [references/testing.md](references/testing.md).
81
+
82
+ **Evals — needed, harness-agnostic.** No deterministic test can catch **mis-selection** (nothing in a unit test decides whether the agent reached for `query_transactions` or `run_sql` — the model chooses, from your descriptions) or **mis-interpretation** (a unit test proves `truncated: true` is present; only an eval proves the agent *noticed* it and didn't sum a partial page into a confident wrong total). Run the real agent against a seeded fixture and grade the transcript on tools called and final answer. Deferring this layer is a resource decision, **not evidence the risk is absent.**
83
+
84
+ **Layout:** keep a tool's deterministic tests **beside the tool**, so tool + tests lift into any project as one unit. Evals are the opposite — cross-cutting, spanning several tools, and centralized. The two layers don't live in the same place.
85
+
86
+ ## Workflows
87
+
88
+ **Writing a new tool** — Start from the workflow the user cares about (Principle 1), not the data model. Draft the name + description + parameters as if they were prompt text (Principles 2 & 5). Decide the return shape and metadata (Principle 3), then add limits, filters, and guard rails (Principle 4). Run the checklist. Then test both layers (see [Testing](#testing)): unit-test the contract — truncation signalled, errors structured, promised fields present — and give the agent 3–5 realistic requests to watch whether it selects, calls, *and interprets* the tool correctly; refine the description where it stumbles.
89
+
90
+ **Reviewing an existing tool** — Walk the checklist top to bottom. For each miss, name the severity, quote the exact line, explain why it trips an agent, and show the fixed version. The most common real failures: bare/colliding names, `param: type` with no description, returning IDs the agent then has to resolve, unbounded responses, and cryptic error codes.
91
+
92
+ ## Failure Modes to Avoid
93
+
94
+ - **One tool per endpoint** — fragments the decision and burns prompt budget. Consolidate.
95
+ - **Bare or colliding names** (`search`, `get`, `fetch`) — the agent can't tell yours apart from another server's. Namespace and be specific.
96
+ - **Undocumented parameters** — `start_date: string` tells the agent nothing about format or bounds. Add format + example + constraints.
97
+ - **Returning IDs instead of context** — forces an extra lookup call and wastes tokens. Return what the agent can reason about.
98
+ - **Unbounded responses** — no limit, no pagination; one call floods the context window. Cap and paginate by default.
99
+ - **Cryptic errors** (`ERR_INVALID_DATE`, `TOO_MANY_RESULTS`) — the agent can't self-correct. Say what happened and what to try next.
100
+ - **Framework tunnel vision** — assuming these ideas only apply to MCP, or only to your language. They apply to every tool surface; see [references/examples.md](references/examples.md).
101
+ - **An unverified contract** — the description promises one thing, the implementation returns another, and nothing notices. Unit-test the checklist items that are mechanically checkable; eval the ones that aren't.
102
+
103
+ ## References
104
+
105
+ - [references/principles.md](references/principles.md) — the five principles in depth, each illustrated with a neutral `name`/`description`/`parameters`/`returns` schema shape (no framework assumed).
106
+ - [references/examples.md](references/examples.md) — the same tool proven across surfaces and languages: one tool in TypeScript (Zod) and Python (Pydantic) side by side, one standalone (non-MCP) tool, and one real MCP-server tool annotated principle by principle.
107
+ - [references/testing.md](references/testing.md) — verifying the contract: which checklist items are mechanically testable and what each assertion looks like, a worked truncation bug (found in real shipped code) with the test that catches it, and what evals catch that no deterministic test can.
@@ -0,0 +1,273 @@
1
+ # Worked Examples: The Same Design Across Surfaces and Languages
2
+
3
+ The point of this file is to *demonstrate* — not just assert — that tool design is framework- and language-agnostic. Each example varies exactly one axis:
4
+
5
+ 1. **[Same tool, two languages](#1-same-tool-two-languages-typescript--python)** — `get_expenses` in TypeScript (Zod) and Python (Pydantic). Varies: language.
6
+ 2. **[A standalone (non-MCP) tool](#2-a-standalone-non-mcp-tool)** — the same tool as a plain function-calling handler, no MCP anywhere. Varies: surface (no server).
7
+ 3. **[A real MCP-server tool](#3-a-real-mcp-server-tool)** — `agentailor_search_articles` from the public `agentailor-mcp` server, annotated principle by principle. Varies: surface (MCP) + it's real shipped code.
8
+
9
+ Read them together: the `name` / `description` / `parameters` / `returns` thinking is identical everywhere; only syntax and registration change.
10
+
11
+ > Sources are all public: the `get_expenses` example is from the published guide **[Writing Effective Tools for AI Agents](https://blog.agentailor.com/blog/writing-tools-for-ai-agents)**; the MCP example is from the public **[agentailor-mcp](https://github.com/agentailor/agentailor-mcp)** server (`src/tools/blog.ts`).
12
+
13
+ ---
14
+
15
+ ## 1. Same tool, two languages (TypeScript + Python)
16
+
17
+ One tool — `get_expenses` — expressed with two different schema libraries. Note that the descriptions, the required/optional split, the defaults, and the return shape are **the same design**; only the binding syntax differs.
18
+
19
+ ### TypeScript (Zod)
20
+
21
+ ```typescript
22
+ import { z } from "zod";
23
+
24
+ const getExpensesSchema = z.object({
25
+ start_date: z
26
+ .string()
27
+ .describe("Start date, ISO format (YYYY-MM-DD). Required. Example: '2025-01-01'"),
28
+ end_date: z
29
+ .string()
30
+ .describe("End date, ISO format (YYYY-MM-DD). Required. Example: '2025-01-31'"),
31
+ category: z
32
+ .enum(["groceries", "dining", "transport", "utilities", "healthcare", "other"])
33
+ .optional()
34
+ .describe("Optional. Filter by category. Omit for all categories."),
35
+ response_format: z
36
+ .enum(["concise", "detailed"])
37
+ .default("concise")
38
+ .describe("'concise' = essential fields; 'detailed' = full metadata. Default 'concise' for token efficiency."),
39
+ limit: z
40
+ .number()
41
+ .int()
42
+ .default(50)
43
+ .describe("Max items to return. Default 50. Lower = fewer tokens."),
44
+ });
45
+
46
+ // description registered alongside the schema (exact binding depends on your framework):
47
+ const description = `Retrieves user expenses within a date range, with optional category filtering.
48
+
49
+ When to use:
50
+ - "What did I spend on groceries last month?"
51
+ - "Show me expenses from January to March"
52
+
53
+ Supports pagination and configurable verbosity. Returns human-readable descriptions and category, not just IDs.`;
54
+ ```
55
+
56
+ ### Python (Pydantic)
57
+
58
+ ```python
59
+ from enum import Enum
60
+ from typing import Optional
61
+ from pydantic import BaseModel, Field
62
+
63
+
64
+ class Category(str, Enum):
65
+ groceries = "groceries"
66
+ dining = "dining"
67
+ transport = "transport"
68
+ utilities = "utilities"
69
+ healthcare = "healthcare"
70
+ other = "other"
71
+
72
+
73
+ class ResponseFormat(str, Enum):
74
+ concise = "concise"
75
+ detailed = "detailed"
76
+
77
+
78
+ class GetExpensesParams(BaseModel):
79
+ start_date: str = Field(
80
+ ..., description="Start date, ISO format (YYYY-MM-DD). Required. Example: '2025-01-01'"
81
+ )
82
+ end_date: str = Field(
83
+ ..., description="End date, ISO format (YYYY-MM-DD). Required. Example: '2025-01-31'"
84
+ )
85
+ category: Optional[Category] = Field(
86
+ None, description="Optional. Filter by category. Omit for all categories."
87
+ )
88
+ response_format: ResponseFormat = Field(
89
+ ResponseFormat.concise,
90
+ description="'concise' = essential fields; 'detailed' = full metadata. Default 'concise' for token efficiency.",
91
+ )
92
+ limit: int = Field(
93
+ 50, description="Max items to return. Default 50. Lower = fewer tokens."
94
+ )
95
+
96
+
97
+ # Same description text as the TS version — the prose is the design, not the language.
98
+ DESCRIPTION = """Retrieves user expenses within a date range, with optional category filtering.
99
+
100
+ When to use:
101
+ - "What did I spend on groceries last month?"
102
+ - "Show me expenses from January to March"
103
+
104
+ Supports pagination and configurable verbosity. Returns human-readable descriptions and category, not just IDs."""
105
+ ```
106
+
107
+ **What's identical (the design) vs. what changed (the syntax):**
108
+
109
+ | Design decision | TS (Zod) | Python (Pydantic) |
110
+ | --- | --- | --- |
111
+ | required `start_date` / `end_date` with format + example | `.describe(...)` | `Field(..., description=...)` |
112
+ | optional `category` enum, omit = all | `.optional()` | `Optional[...] = Field(None, ...)` |
113
+ | `response_format` default `concise` (token efficiency) | `.default("concise")` | `Field(ResponseFormat.concise, ...)` |
114
+ | `limit` default 50 | `.default(50)` | `Field(50, ...)` |
115
+ | what/when/how description | string literal | string literal |
116
+
117
+ The five principles live in the left column. The right two columns are just bindings.
118
+
119
+ ---
120
+
121
+ ## 2. A standalone (non-MCP) tool
122
+
123
+ The same tool as a plain handler a model calls directly (OpenAI/Anthropic-style function calling, or any in-process agent framework). **No MCP, no server** — proof that the principles aren't MCP-bound. This mirrors the handler from the published guide.
124
+
125
+ ```typescript
126
+ // Function-calling definition (framework-neutral JSON schema shape)
127
+ const getExpensesTool = {
128
+ name: "get_expenses",
129
+ description: `Retrieves user expenses within a date range. Use for spending analysis or budget tracking.
130
+ When to use: "What did I spend on groceries last month?", "Show me expenses from January to March".`,
131
+ parameters: {
132
+ type: "object",
133
+ properties: {
134
+ start_date: { type: "string", description: "Start date, ISO (YYYY-MM-DD). Required. Example: '2025-01-01'" },
135
+ end_date: { type: "string", description: "End date, ISO (YYYY-MM-DD). Required. Example: '2025-01-31'" },
136
+ category: { type: "string", enum: ["groceries","dining","transport","utilities","healthcare","other"],
137
+ description: "Optional. Filter by category. Omit for all." },
138
+ response_format: { type: "string", enum: ["concise","detailed"], default: "concise",
139
+ description: "'concise' = essentials; 'detailed' = full metadata. Default 'concise'." },
140
+ limit: { type: "number", default: 50, description: "Max items. Default 50. Lower = fewer tokens." },
141
+ },
142
+ required: ["start_date", "end_date"],
143
+ },
144
+ };
145
+
146
+ // Handler — defensive design in the body: validate, guard, truncate loudly, return context.
147
+ async function handleGetExpenses(p) {
148
+ const { start_date, end_date, category, response_format = "concise", limit = 50 } = p;
149
+
150
+ // Principle 5: helpful errors the agent can act on
151
+ const iso = /^\d{4}-\d{2}-\d{2}$/;
152
+ if (!iso.test(start_date) || !iso.test(end_date)) {
153
+ return { error: "Invalid date format. Use YYYY-MM-DD. Example: '2025-01-15'.",
154
+ received: { start_date, end_date } };
155
+ }
156
+ const start = new Date(start_date), end = new Date(end_date);
157
+ if (start > end) return { error: "start_date must be before end_date.", received: { start_date, end_date } };
158
+
159
+ // Principle 4: guard responses that would blow the context window
160
+ const days = Math.ceil((+end - +start) / 86_400_000);
161
+ if (days > 365) {
162
+ return { error: "Date range too large (>365 days). Consumes excessive tokens.",
163
+ suggestion: "Use a smaller range (e.g. monthly) or add a category filter." };
164
+ }
165
+
166
+ let expenses = await db.getExpenses({ start, end, category });
167
+
168
+ // Principle 4: truncate loudly, guide the next query
169
+ if (expenses.length > limit) {
170
+ const total = expenses.length;
171
+ expenses = expenses.slice(0, limit);
172
+ return {
173
+ notice: `Found ${total} expenses; returning the first ${limit} to preserve tokens.`,
174
+ guidance: category ? "Narrow the date range." : "Add a category filter to focus results.",
175
+ summary: { total_found: total, returned: limit },
176
+ expenses: format(expenses, response_format),
177
+ };
178
+ }
179
+
180
+ // Principle 3: meaningful context + metadata, not bare IDs
181
+ return {
182
+ query: { start_date, end_date, category: category ?? "all categories" },
183
+ summary: { total_expenses: expenses.length,
184
+ total_amount: expenses.reduce((s, e) => s + e.amount, 0), currency: "USD" },
185
+ expenses: format(expenses, response_format),
186
+ };
187
+ }
188
+
189
+ // Principle 3: concise vs detailed — configurable verbosity
190
+ function format(expenses, mode) {
191
+ return expenses.map((e) =>
192
+ mode === "concise"
193
+ ? { date: e.date, amount: e.amount, category: e.category, description: e.description }
194
+ : { date: e.date, amount: e.amount, category: e.category, description: e.description,
195
+ merchant: e.merchant, payment_method: e.paymentMethod, tags: e.tags, notes: e.notes });
196
+ }
197
+ ```
198
+
199
+ Every principle is present, and MCP never appears. The exact same handler drops into an MCP server's tool executor unchanged — which is the whole point.
200
+
201
+ ---
202
+
203
+ ## 3. A real MCP-server tool
204
+
205
+ `agentailor_search_articles`, shipped in the public [agentailor-mcp](https://github.com/agentailor/agentailor-mcp) server (`src/tools/blog.ts`, FastMCP). This is real code, and it independently lands all five principles — evidence the standard holds up in production, not just in illustrations.
206
+
207
+ ```typescript
208
+ server.addTool({
209
+ // Principle 2: namespaced, descriptive name — no collision with any other server's "search"
210
+ name: "agentailor_search_articles",
211
+ // Principles 2 & 5: what / when / how, with example queries and the return contract
212
+ description: `Searches the Agentailor blog and returns a ranked shortlist of matching articles as JSON. One tool for all discovery: free-text, by tag, and guides-only.
213
+
214
+ **When to use:**
215
+ - "What articles cover MCP?" with query: "mcp"
216
+ - "Show me everything tagged langgraph and tools" with tags: ["langgraph", "tools"]
217
+ - "Which complete guides do you have?" with guidesOnly: true
218
+ - Combine them: query + tags + guidesOnly all narrow together.
219
+
220
+ Returns JSON: { results, total, shown, hint? }. Each result carries the article's .md URL in results[].url; pass that to agentailor_read_article to read one in full.`,
221
+ parameters: z.object({
222
+ // Principle 1: one discovery tool that consolidates free-text + tag + guides filtering,
223
+ // instead of search_by_text / search_by_tag / list_guides as three separate tools
224
+ query: z.string().optional().describe(
225
+ 'Free-text terms matched against title, summary, and tags. Multiple words matched individually and ranked. Example: "memory". Omit to list everything.'
226
+ ),
227
+ tags: z.array(z.string()).optional().describe(
228
+ 'Filter to articles carrying ALL of these tags. Example: ["mcp", "security"].'
229
+ ),
230
+ guidesOnly: z.boolean().optional().describe("If true, return only complete guides. Default: false."),
231
+ // Principle 4: token efficiency — limit with an explicit "lower saves tokens" note
232
+ limit: z.number().int().min(1).max(100).optional().describe(
233
+ "Max results to return. Lower values save tokens."
234
+ ),
235
+ // Principle 3: configurable verbosity
236
+ response_format: z.enum(["concise", "detailed"]).optional().describe(
237
+ 'Output verbosity. "concise" (default) returns title, url, and guide per result; "detailed" adds date, tags, and summary.'
238
+ ),
239
+ }),
240
+ execute: async ({ query, tags, guidesOnly, limit, response_format }) => {
241
+ const posts = await getPosts();
242
+ const matches = searchPosts(posts, { query, tags, guidesOnly });
243
+ const cap = limit ?? SEARCH_LIMIT_DEFAULT;
244
+ const shown = matches.slice(0, cap);
245
+ // Principle 3: returns total + shown metadata and each result's .md URL —
246
+ // meaningful context the agent chains straight into agentailor_read_article, no lookup
247
+ const response = buildSearchResponse(shown, matches.length, cap, response_format ?? "concise");
248
+ return JSON.stringify(response, null, 2);
249
+ },
250
+ });
251
+ ```
252
+
253
+ Its sibling `agentailor_read_article` closes the loop with **Principle 5** error handling — when the agent passes a bad URL it doesn't get a cryptic code, it gets told how to recover:
254
+
255
+ ```typescript
256
+ throw new UserError(
257
+ `No article found at ${url}. Check the URL against agentailor_search_articles results.`
258
+ );
259
+ ```
260
+
261
+ **Principle-by-principle scorecard for this real tool:**
262
+
263
+ - **Strategic** — one `search_articles` covering free-text, tags, and guides, rather than three fragmented tools.
264
+ - **Named** — `agentailor_` prefix guarantees no collision with another server's `search`.
265
+ - **Contextual** — returns `results/total/shown` plus each article's `.md` URL, so the agent reasons and chains without a second lookup.
266
+ - **Efficient** — bounded `limit` (max 100) with a token note, plus `response_format` for verbosity.
267
+ - **Prompt-shaped** — the description gives example queries and states the exact return contract; the companion tool's errors guide recovery.
268
+
269
+ ---
270
+
271
+ ## The takeaway
272
+
273
+ Three surfaces, two languages, one design. When you write your next tool — in any framework, in any language — you're filling in the same four slots (`name`, `description`, `parameters`, `returns`) against the same five principles. Start from [SKILL.md](../SKILL.md)'s checklist; reach for [principles.md](principles.md) when you need the reasoning behind a decision.