|
1 | 1 | # Resource Templates |
| 2 | + |
| 3 | +👨💼 Now that you've registered a static resource, let's make things more dynamic! |
| 4 | +In this step, you'll use MCP's resource templates to expose a whole family of |
| 5 | +resources—each with its own unique URI and data. |
| 6 | + |
| 7 | +Resource templates let you define parameterized resources, like `entry://{id}` |
| 8 | +or `tag://{id}`. This means clients can discover and read individual entries or |
| 9 | +tags by their unique identifiers, just like accessing a file by its path. |
| 10 | + |
| 11 | +Here's a dynamic "hello world" resource template example that reads names from a |
| 12 | +database: |
| 13 | + |
| 14 | +```ts |
| 15 | +import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js' |
| 16 | + |
| 17 | +agent.server.resource( |
| 18 | + 'hello', |
| 19 | + new ResourceTemplate('hello://{name}', { |
| 20 | + list: async () => { |
| 21 | + // Imagine this is a call to your database to get all names |
| 22 | + const names = await db.getAllNames() |
| 23 | + return { |
| 24 | + resources: names.map((name) => ({ |
| 25 | + name, |
| 26 | + uri: `hello://${name}`, |
| 27 | + mimeType: 'text/plain', |
| 28 | + })), |
| 29 | + } |
| 30 | + }, |
| 31 | + }), |
| 32 | + { description: 'Say hello to anyone by name!' }, |
| 33 | + async (uri, { name }) => { |
| 34 | + return { |
| 35 | + contents: [ |
| 36 | + { |
| 37 | + mimeType: 'text/plain', |
| 38 | + text: `Hello, ${name}!`, |
| 39 | + uri: uri.toString(), |
| 40 | + }, |
| 41 | + ], |
| 42 | + } |
| 43 | + }, |
| 44 | +) |
| 45 | +``` |
| 46 | + |
| 47 | +Notice how the `list` callback queries the database and returns a resource |
| 48 | +listing for each name. This pattern is exactly what you'll use to expose entries |
| 49 | +and tags from your own database. |
| 50 | + |
| 51 | +Your goal in this step: |
| 52 | + |
| 53 | +- Use resource templates to expose entries and tags from your database, each |
| 54 | + accessible by a unique URI. |
| 55 | +- Make sure clients can list all available entries and tags (using the `list` |
| 56 | + callback), and read the details for any specific one. |
0 commit comments