### Resource: config_file Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Example of a resource with URI template completions, showing how to implement the complete() method to provide suggestions for path parameters. ```APIDOC ## [Resource] config_file ### Description Provides access to configuration files by directory and name. Supports completions for path parameters to help users fill in values interactively. ### Resource URI `file://{directory}/{name}.txt` ### MIME Type `text/plain` ### Parameters #### Path Parameters - **directory** (string) - Required - The directory containing the configuration file. - **name** (string) - Required - The name of the configuration file (without extension). ### Request Example ``` No request body. The resource is accessed via its URI with the `directory` and `name` path parameters. ``` ### Response #### Success Response (200) - **content** (string) - The configuration file content as plain text. #### Response Example ``` Content-Type: text/plain [Configuration file content] ``` ### Completions Provides suggestions for path parameters when the user is filling them in. #### Completion for `name` - **values**: `config`, `settings`, `environment`, `database` #### Completion for `directory` - **values**: `production`, `staging`, `development` #### Completion for other parameters - **values**: `[]` (empty) ``` -------------------------------- ### Combining multiple annotations example Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Shows how to combine @isReadOnly(), @isOpenWorld(), and @isIdempotent() on the same tool. The example defines a SearchOnlineTool that searches online and is safe to call repeatedly. ```typescript import { isReadOnly, isOpenWorld, isIdempotent } from '@jrmc/adonis-mcp/tool_annotations' @isReadOnly() @isOpenWorld() @isIdempotent() export default class SearchOnlineTool extends Tool { name = 'search_online' async handle({ args, response }: ToolContext) { const results = await searchEngine.search(args?.query) return response.text(JSON.stringify(results)) } } ``` -------------------------------- ### Install Bouncer with node ace add Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/authentication.md Run this command to install and configure @adonisjs/bouncer. It creates the abilities file (app/abilities/main.ts), the policies directory, and the initialize_bouncer_middleware. ```bash node ace add @adonisjs/bouncer ``` -------------------------------- ### MCP configuration with completions enabled Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/installation.md Example configuration with the completions option set to true, enabling argument completions for prompts and resources. ```typescript import { defineConfig } from '@jrmc/adonis-mcp' export default defineConfig({ name: 'adonis-mcp-server', version: '1.0.0', completions: true, // Enable completions }) ``` -------------------------------- ### Schema-less tool example (GetServerTimeTool) Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Shows how to define a tool without a schema when no input parameters are needed. It uses `response.text()` to return the current server time. ```typescript import type { ToolContext } from '@jrmc/adonis-mcp/types/context' import { Tool } from '@jrmc/adonis-mcp' export default class GetServerTimeTool extends Tool { name = 'get_server_time' title = 'Get Server Time' description = 'Returns the current server time' async handle({ response }: ToolContext) { const currentTime = new Date().toISOString() return response.text(`Current server time: ${currentTime}`) } } ``` -------------------------------- ### Install the adonis-mcp skill with npx Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/skills.md Run this command from the root of your AdonisJS project to install the agent skill. The CLI detects your agent (e.g., Claude Code, Cursor, Codex) and installs the skill in the appropriate location, such as .claude/skills/ for Claude Code. ```bash npx skills add batosai/adonis-mcp ``` -------------------------------- ### Create and run AdonisJS MCP starter kit Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/starter.md Create a new AdonisJS project using the MCP starter kit, then move into the project and start the development server. The MCP server will be available at http://localhost:3333/mcp. ```bash npm init adonisjs@latest -- -K="batosai/adonisjs-mcp-starter-kit" my-mcp-server ``` ```bash cd my-mcp-server npm run dev ``` -------------------------------- ### Install @jrmc/adonis-mcp via Ace Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/index.md Run the Ace command 'add' to install the package into your AdonisJS project. This is the primary installation step before registering routes and creating tools. ```bash node ace add @jrmc/adonis-mcp ``` -------------------------------- ### Run the MCP Inspector Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/inspector.md Command to start the MCP Inspector using HTTP transport by default. Requires a development environment. ```bash node ace mcp:inspector ``` -------------------------------- ### Create a bookmark tool with schema Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Complete example of a tool that creates a bookmark. It defines a schema with title and url string properties, uses the auth user's id, and returns a text response with the created bookmark. ```typescript import type { ToolContext } from '@jrmc/adonis-mcp/types/context' import type { BaseSchema } from '@jrmc/adonis-mcp/types/method' import { Tool } from '@jrmc/adonis-mcp' import Bookmark from '#models/bookmark' type Schema = BaseSchema<{ title: { type: "string" } url: { type: "string" } }> export default class AddBookmarkTool extends Tool { name = 'create_bookmark' title = 'Create Bookmark' description = 'Create a new bookmark' async handle({ args, response, auth }: ToolContext) { const bookmark = await Bookmark.create({ title: args.title, text: args.url, userId: auth?.user?.id, }) return response.text(JSON.stringify({ bookmark })) } schema() { return { type: "object", properties: { title: { type: "string", description: "Bookmark title" }, url: { type: "string", description: "Bookmark URL" } }, required: ["title", "url"] } as Schema } } ``` -------------------------------- ### Define a complete resource with authentication and metadata Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Complete resource example showing how to define a resource with URI template, annotations, and authentication. The handle method queries a document by ID and user ownership, throwing an error if authentication is missing. Returns text content with metadata and sets the resource size. ```typescript import type { ResourceContext } from '@jrmc/adonis-mcp/types/context' import { Resource } from '@jrmc/adonis-mcp' import { priority, audience } from '@jrmc/adonis-mcp/annotations' import Role from '@jrmc/adonis-mcp/enums/role' import Document from '#models/document' type Args = { id: string } @priority(0.7) @audience([Role.USER, Role.ASSISTANT]) export default class UserDocumentResource extends Resource { name = 'user_document' uri = 'document:///{id}' mimeType = 'text/plain' title = 'User Document' description = 'Access user documents by ID' async handle({ args, auth, response }: ResourceContext) { const user = auth?.user if (!user) { throw new Error('Authentication required') } const document = await Document.query() .where('id', args?.id) .where('userId', user.id) .firstOrFail() this.size = document.content.length return response.text(document.content).withMeta({ documentId: document.id, createdAt: document.createdAt.toISOString(), updatedAt: document.updatedAt.toISOString() }) } } ``` -------------------------------- ### Enable and implement resource completions for URI templates Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Two-step setup for resource completions: first enable completions in config/mcp.ts with the completions flag, then implement the complete() method in the resource. The complete method returns suggestions for path parameters based on which parameter is being completed, with empty values as fallback. ```typescript import { defineConfig } from '@jrmc/adonis-mcp' export default defineConfig({ name: 'adonis-mcp-server', version: '1.0.0', completions: true, // Enable completions }) ``` ```typescript import type { ResourceContext, CompleteContext } from '@jrmc/adonis-mcp/types/context' import { Resource } from '@jrmc/adonis-mcp' type Args = { directory: string name: string } export default class ConfigFileResource extends Resource { name = 'config_file' uri = 'file://{directory}/{name}.txt' mimeType = 'text/plain' async handle({ args, response }: ResourceContext) { const content = await readConfigFile(args?.directory, args?.name) return response.text(content) } async complete({ args, response }: CompleteContext) { // Provide suggestions based on what's being completed if (args?.name !== undefined) { return response.complete({ values: ['config', 'settings', 'environment', 'database'] }) } if (args?.directory !== undefined) { return response.complete({ values: ['production', 'staging', 'development'] }) } return response.complete({ values: [] }) } } ``` -------------------------------- ### URI Format Examples for MCP Resources Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Shows common URI schemes for MCP resources, including file, web, and custom schemes. Use these to ensure each resource URI is valid and unique. ```typescript // File resource uri = 'file:///documents/readme.txt' // Web resource uri = 'https://api.example.com/data' // Custom scheme uri = 'myapp://users/profile' ``` -------------------------------- ### @isOpenWorld() annotation example Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Use @isOpenWorld() to indicate a tool can access information from the internet or external sources. The example shows a FetchWeatherTool that calls an external API. ```typescript import { isOpenWorld } from '@jrmc/adonis-mcp/tool_annotations' @isOpenWorld() export default class FetchWeatherTool extends Tool { name = 'fetch_weather' async handle({ args, response }: ToolContext) { const weather = await externalApi.getWeather(args?.city) return response.text(JSON.stringify(weather)) } } ``` -------------------------------- ### Adonis MCP Tool: greet_tool.ts Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/index.md Defines a simple MCP tool that extends the base Tool class from '@jrmc/adonis-mcp'. The tool has a name, description, and a handle method that returns a text response using the 'response.text' helper. This is a minimal example to get started with building MCP tools in AdonisJS. ```typescript import { Tool } from '@jrmc/adonis-mcp' export default class GreetTool extends Tool { name = 'greet' description = 'Welcome a user' async handle({ response }) { return response.text('Welcome!') } } ``` -------------------------------- ### createPromptsGetRequest helper usage Source: https://github.com/batosai/adonis-mcp/blob/2.x/tests/README.md Creates a request to get a prompt. ```typescript import { createPromptsGetRequest } from '../helpers/create_request.js' const request = createPromptsGetRequest('my-prompt', { text: 'Hello' }) ``` -------------------------------- ### Complete CodeReviewPrompt class with schema and handle method Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Complete example of a prompt class for code review. It defines a schema with code and language properties, and returns an array of text responses in the handle method. ```typescript import type { PromptContext } from '@jrmc/adonis-mcp/types/context' import type { BaseSchema } from '@jrmc/adonis-mcp/types/method' import { Prompt } from '@jrmc/adonis-mcp' type Schema = BaseSchema<{ code: { type: "string" } language: { type: "string" } }> export default class CodeReviewPrompt extends Prompt { name = 'code_review' title = 'Code Review' description = 'Review code and provide feedback' async handle({ args, response }: PromptContext) { return [ response.text(`Please review this ${args.language} code:\n\n${args.code}`), response.text('Provide feedback on code quality, potential bugs, and improvements.') ] } schema() { return { type: "object", properties: { code: { type: "string", description: "The code to review" }, language: { type: "string", description: "Programming language" } }, required: ["code", "language"] } as Schema } } ``` -------------------------------- ### Implement tool handler with handle method Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Example implementation of the handle method. Receives a typed context with validated arguments and returns a text response. The context includes auth and bouncer for authorization. ```typescript async handle({ args, response, auth, bouncer }: ToolContext) { // Your logic here const result = await SomeModel.query().where('id', args.id) return response.text(JSON.stringify({ result })) } ``` -------------------------------- ### CodeReviewPrompt class extending Prompt with completions Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/prompts.md Complete example of a prompt for code review with completions. Defines a Prompt subclass with handle, complete, and schema methods. Uses response.text, response.embeddedResource, and response.complete to build the prompt and provide suggestions for language and focus. ```typescript import type { PromptContext, CompleteContext } from '@jrmc/adonis-mcp/types/context' import type { BaseSchema } from '@jrmc/adonis-mcp/types/method' import { Prompt } from '@jrmc/adonis-mcp' type Schema = BaseSchema<{ code: { type: "string" } language: { type: "string" } focus: { type: "string" } }> export default class CodeReviewPrompt extends Prompt { name = 'code_review' title = 'Code Review' description = 'Review code and provide detailed feedback' async handle({ args, response, auth }: PromptContext) { const user = auth?.user const greeting = user ? `Hello ${user.name},` : 'Hello,' return [ response.text(greeting), response.text(`Please perform a ${args?.focus} review of this ${args?.language} code:`), response.text('```' + args?.language), response.text(args?.code), response.text('```'), response.embeddedResource('file:///guidelines/code-review-checklist.md'), response.text('Provide feedback following the checklist above.') ] } async complete({ args, response }: CompleteContext) { // Language suggestions if (args?.language !== undefined) { return response.complete({ values: [ 'javascript', 'typescript', 'python', 'java', 'go', 'rust', 'php', 'ruby' ] }) } // Focus area suggestions if (args?.focus !== undefined) { return response.complete({ values: [ 'security', 'performance', 'maintainability', 'best practices', 'bug detection', 'code style' ] }) } return response.complete({ values: [] }) } schema() { return { type: "object", properties: { code: { type: "string", description: "The code to review" }, language: { type: "string", description: "Programming language" }, focus: { type: "string", description: "Area to focus on (security, performance, etc.)", default: "general" } }, required: ["code", "language"] } as Schema } } ``` -------------------------------- ### Resource: user_document Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Complete example of a resource that provides access to user documents, including authentication, querying, and response with metadata. ```APIDOC ## [Resource] user_document ### Description Provides access to user documents by ID. This resource is used to retrieve a document's content as plain text, along with metadata about the document. ### Resource URI `document:///{id}` ### MIME Type `text/plain` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the document to retrieve. ### Request Example ``` No request body. The resource is accessed via its URI with the `id` path parameter. ``` ### Response #### Success Response (200) - **content** (string) - The document content as plain text. - **meta** (object) - Additional metadata including: - **documentId** (string) - The ID of the document. - **createdAt** (string) - ISO timestamp of document creation. - **updatedAt** (string) - ISO timestamp of last update. #### Response Example ``` Content-Type: text/plain [Document content] X-Meta-DocumentId: 123 X-Meta-CreatedAt: 2023-01-01T00:00:00.000Z X-Meta-UpdatedAt: 2023-01-02T00:00:00.000Z ``` ### Error Handling - **Authentication required** - Throws an error if no authenticated user is present. - **Document not found** - Throws an error if the document does not exist or does not belong to the authenticated user. ``` -------------------------------- ### Generate Documentation Prompt (generate_docs) Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/prompts.md Defines a prompt class named 'generate_docs' that instructs the model to generate comprehensive documentation for provided code, covering function/class descriptions, parameters, return values, usage examples, and edge cases. ```typescript export default class GenerateDocsPrompt extends Prompt { name = 'generate_docs' title = 'Generate Documentation' description = 'Generate documentation for code' async handle({ args, response }: PromptContext) { return [ response.text('Generate comprehensive documentation for the following code:'), response.text(args?.code), response.text('Include:'), response.text('- Function/class description'), response.text('- Parameter explanations'), response.text('- Return value description'), response.text('- Usage examples'), response.text('- Edge cases and error handling') ] } } ``` -------------------------------- ### Prompt handler returning multiple content objects Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Example of a handle method that returns an array with text and an embedded resource. ```typescript async handle({ args, response }: PromptContext) { return [ response.text(`Please review this code:\n\n${args.code}`), response.embeddedResource('file:///example.txt') ] } ``` -------------------------------- ### TypeScript type safety examples with bouncer.authorize and policy authorize Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/authentication.md Demonstrates TypeScript autocompletion and type errors for bouncer calls. Shows valid authorize calls with abilities and policies, and invalid calls reporting unknown ability and wrong arguments. ```typescript // ✅ Autocompletion on ability names await bouncer.authorize(editUser) // ✅ Autocompletion on policy methods and their arguments await bouncer.with(UserPolicy).authorize('view', user) // ❌ TypeScript error — unknown ability await bouncer.authorize(unknownAbility) // ❌ TypeScript error — wrong arguments for policy method await bouncer.with(UserPolicy).authorize('view') ``` -------------------------------- ### JSON Schema definition for tool input Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Example schema definition following the JSON Schema specification. Defines input parameters for a tool, including required fields. ```typescript schema() { return { type: "object", properties: { title: { type: "string", description: "Bookmark title" }, url: { type: "string", description: "Bookmark URL" } }, required: ["title", "url"] } as Schema } ``` -------------------------------- ### Attach metadata with withMeta() Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Example of using withMeta() on text content to attach custom metadata for MCP clients. Available on text, image, audio, blob, resource link, and embedded resource content. Structured responses do not support withMeta(). ```typescript async handle({ args, response }: ToolContext) { const users = await User.all() return response.text(JSON.stringify(users)).withMeta({ source: 'database', queryTime: Date.now(), count: users.length, cacheHit: false }) } ``` -------------------------------- ### Test MCP prompt get end-to-end Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/unit-tests.md Tests the prompts/get method end-to-end using a fake transport. Registers a prompt, initializes the server, sends a prompts/get request, and asserts the response contains the expected message content. ```typescript test.group('MCP Prompt Integration', () => { test('should handle prompt get end-to-end', async ({ assert }) => { const server = new Server({ name: 'Test Server', version: '1.0.0' }) // Register your prompt server.addPrompt({ 'my_prompt': app.makePath('app/mcp/prompts/my_prompt_prompt.ts') }) const transport = new FakeTransport() await server.connect(transport) await server.handle({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }) // Get the prompt await server.handle({ jsonrpc: '2.0', id: 2, method: 'prompts/get', params: { name: 'my_prompt', arguments: { text: 'Hello' } } }) const lastMessage = transport.getLastMessage() const result = lastMessage?.result as GetPromptResult const content = result?.messages[0].content as TextContent assert.exists(lastMessage) assert.equal(lastMessage?.id, 2) assert.exists(result) assert.isArray(result.messages) assert.equal(result.messages[0].role, 'user') assert.equal(content.text, 'Hello, world!') }) }) ``` -------------------------------- ### Run MCP Inspector with HTTP or stdio transport Source: https://github.com/batosai/adonis-mcp/blob/2.x/skills/adonis-mcp/references/testing.md Starts the MCP Inspector for interactive debugging. The first command uses the HTTP transport (default), the second uses stdio. Development environment only; refuses to run in production. Creates a writable .mcp-inspector.json catalog at the application root when needed and preserves existing settings. ```bash node ace mcp:inspector # HTTP transport (default) node ace mcp:inspector stdio # stdio transport ``` -------------------------------- ### Create a new MCP server with the starter kit Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/installation.md Use this command to scaffold a dedicated MCP server with the AdonisJS MCP Starter Kit. It creates a lightweight AdonisJS application pre-configured with MCP support. ```bash npm init adonisjs@latest -- -K="batosai/adonisjs-mcp-starter-kit" my-mcp-server ``` -------------------------------- ### Register VineJS provider in adonisrc.ts Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/validation.md Adds the VineJS provider manually in adonisrc.ts to enable VineJS validation after installation. Required if the installer was answered No. ```typescript providers: [ // ... '@jrmc/adonis-mcp/vinejs_provider', ] ``` -------------------------------- ### Simple Resource Handler Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Returns static text content 'Hello, World!' and sets the resource size to the content length. Use for fixed content that requires no context. ```typescript async handle({ response }: ResourceContext) { const content = 'Hello, World!' this.size = content.length return response.text(content) } ``` -------------------------------- ### @isDestructive() annotation example Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Use @isDestructive() to indicate a tool performs destructive operations like deleting data. The example shows a DeleteUserTool that deletes a user by ID. ```typescript import { isDestructive } from '@jrmc/adonis-mcp/tool_annotations' @isDestructive() export default class DeleteUserTool extends Tool { name = 'delete_user' async handle({ args, response }: ToolContext) { await User.query().where('id', args?.id).delete() return response.text('User deleted successfully') } } ``` -------------------------------- ### @isIdempotent() annotation example Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Use @isIdempotent() to indicate a tool can be safely called multiple times with the same arguments without causing different effects. The example shows a SetUserStatusTool that updates a user's status. ```typescript import { isIdempotent } from '@jrmc/adonis-mcp/tool_annotations' @isIdempotent() export default class SetUserStatusTool extends Tool { name = 'set_user_status' async handle({ args, response }: ToolContext) { await User.query().where('id', args?.id).update({ status: args?.status }) return response.text('Status updated') } } ``` -------------------------------- ### Project structure of AdonisJS MCP starter kit Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/starter.md Shows the directory layout of a project created with the starter kit. The mcp/ directory at the project root holds tools, resources, and prompts. ```text my-mcp-server/ ├── app/ │ ├── exceptions/ │ │ └── handler.ts │ └── middleware/ │ ├── container_bindings_middleware.ts │ └── mcp_middleware.ts ├── bin/ │ ├── console.ts │ ├── mcp.ts # Stdio transport entry point │ ├── server.ts │ └── test.ts ├── config/ │ ├── app.ts │ ├── bodyparser.ts │ ├── encryption.ts │ ├── hash.ts │ ├── logger.ts │ └── mcp.ts # MCP server configuration ├── mcp/ │ ├── tools/ # Your MCP tools go here │ ├── resources/ # Your MCP resources go here │ └── prompts/ # Your MCP prompts go here ├── start/ │ ├── env.ts │ ├── kernel.ts │ └── routes.ts ├── tests/ │ └── bootstrap.ts ├── adonisrc.ts ├── package.json └── tsconfig.json ``` -------------------------------- ### @isReadOnly() annotation example Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Use @isReadOnly() to indicate a tool only reads data and does not modify state. The example shows a GetUserTool that fetches a user by ID. You can also explicitly set it to false with @isReadOnly(false). ```typescript import { Tool } from '@jrmc/adonis-mcp' import { isReadOnly } from '@jrmc/adonis-mcp/tool_annotations' @isReadOnly() export default class GetUserTool extends Tool { name = 'get_user' async handle({ args, response }: ToolContext) { const user = await User.find(args?.id) return response.text(JSON.stringify(user)) } } ``` ```typescript @isReadOnly(false) export default class UpdateUserTool extends Tool { // ... } ``` -------------------------------- ### Stdio entry point for MCP server in bin/mcp.ts Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/starter.md Boots the AdonisJS application and launches the MCP server over stdio. This entry point is useful for AI clients that communicate via standard input/output, such as Claude Desktop or Cursor. ```typescript new Ignitor(APP_ROOT, { importer: IMPORTER }) .tap((app) => { app.booting(async () => { await import('#start/env') }) app.listen('SIGTERM', () => app.terminate()) app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate()) }) .ace() .handle(['mcp:start']) ``` -------------------------------- ### @lastModified() annotation example Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Indicates when a resource was last updated using an ISO 8601 timestamp. ```typescript import { Resource } from '@jrmc/adonis-mcp' import { lastModified } from '@jrmc/adonis-mcp/annotations' @lastModified('2024-12-12T10:00:00Z') export default class DocumentResource extends Resource { name = 'document.txt' uri = 'file:///document.txt' async handle({ response }: ResourceContext) { return response.text('Document content') } } ``` -------------------------------- ### Create a resource with node ace make:mcp-resource Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Creates a new resource file at app/mcp/resources/my_resource.ts with a base template. ```bash node ace make:mcp-resource my_resource ``` -------------------------------- ### Test MCP server initialization capabilities Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/unit-tests.md Verifies that the server initializes with the correct capabilities. Registers a tool, resource, and prompt, then sends an initialize request and asserts the server info and capability fields are present. ```typescript test.group('MCP Server', () => { test('should initialize with correct capabilities', async ({ assert }) => { const server = new Server({ name: 'Test Server', version: '1.0.0' }) server.addTool({ 'my_tool': app.makePath('app/mcp/tools/my_tool_tool.ts') }) server.addResource({ 'file:///doc.txt': app.makePath('app/mcp/resources/document_resource.ts') }) server.addPrompt({ 'my_prompt': app.makePath('app/mcp/prompts/my_prompt_prompt.ts') }) const transport = new FakeTransport() await server.connect(transport) await server.handle({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'Test Client', version: '1.0.0' } } }) const lastMessage = transport.getLastMessage() const result = lastMessage?.result as InitializeResult assert.exists(lastMessage) assert.exists(result) assert.equal(result.serverInfo.name, 'Test Server') assert.equal(result.serverInfo.version, '1.0.0') assert.exists(result.capabilities) assert.exists(result.capabilities.tools) assert.exists(result.capabilities.resources) assert.exists(result.capabilities.prompts) }) }) ``` -------------------------------- ### Generate a new MCP tool with ace Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/starter.md Run this command to create a new MCP tool named 'hello'. It generates the file mcp/tools/hello_tool.ts. ```bash node ace make:mcp-tool hello ``` -------------------------------- ### Enable completions and implement complete() method Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/prompts.md Enable completions in the MCP configuration and implement the complete() method in a prompt class. The config sets completions: true, and the prompt provides language suggestions when the language argument is provided. ```typescript import { defineConfig } from '@jrmc/adonis-mcp' export default defineConfig({ name: 'adonis-mcp-server', version: '1.0.0', completions: true, // Enable completions }) ``` ```typescript import type { PromptContext, CompleteContext } from '@jrmc/adonis-mcp/types/context' import type { BaseSchema, InferJSONSchema } from '@jrmc/adonis-mcp/types/method' import { Prompt } from '@jrmc/adonis-mcp' type Schema = BaseSchema<{ language: { type: "string" } code: { type: "string" } }> export default class CodeReviewPrompt extends Prompt { name = 'code_review' title = 'Code Review' description = 'Review code and provide feedback' async handle({ args, response }: PromptContext) { return [ response.text(`Please review this ${args?.language} code:`), response.text(args?.code) ] } async complete({ args, response }: CompleteContext>) { // Provide language suggestions when the user types if (args?.language !== undefined) { return response.complete({ values: ['python', 'javascript', 'typescript', 'java', 'go', 'rust'] }) } return response.complete({ values: [] }) } schema() { return { type: "object", properties: { language: { type: "string", description: "Programming language" }, code: { type: "string", description: "Code to review" } }, required: ["language", "code"] } as Schema } } ``` -------------------------------- ### Resource handler reading file content Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Example of a handle method that reads a file and returns its content as text, updating the size property. ```typescript async handle({ response }: ResourceContext) { const content = await fs.readFile('path/to/file.txt', 'utf-8') this.size = content.length return response.text(content) } ``` -------------------------------- ### @audience() annotation example Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Specifies the intended audience for a resource (user, assistant, or both). Uses Role.USER for end users and Role.ASSISTANT for AI assistants. ```typescript import { Resource } from '@jrmc/adonis-mcp' import { audience } from '@jrmc/adonis-mcp/annotations' import Role from '@jrmc/adonis-mcp/enums/role' @audience(Role.USER) export default class UserManualResource extends Resource { name = 'user_manual.txt' uri = 'file:///user_manual.txt' async handle({ response }: ResourceContext) { return response.text('User manual content') } } ``` -------------------------------- ### @priority() annotation example Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Specifies the importance of a resource as a number between 0.0 and 1.0. Higher values indicate more important resources that AI clients should prioritize. ```typescript import { Resource } from '@jrmc/adonis-mcp' import { priority } from '@jrmc/adonis-mcp/annotations' @priority(0.9) export default class ImportantDocResource extends Resource { name = 'important_doc.txt' uri = 'file:///important_doc.txt' async handle({ response }: ResourceContext) { return response.text('Critical documentation content') } } ``` -------------------------------- ### Run all tests with npm test Source: https://github.com/batosai/adonis-mcp/blob/2.x/tests/README.md Command to run the entire test suite. ```bash npm test ``` -------------------------------- ### Return structured output with response.structured() Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Example of using response.structured() to return JSON data in a structured format. Structured content can only be used in tools, not in prompts or resources. ```typescript import type { ToolContext } from '@jrmc/adonis-mcp/types/context' import { Tool } from '@jrmc/adonis-mcp' export default class GetWeatherTool extends Tool { name = 'get_weather' title = 'Get Weather' description = 'Get current weather data' async handle({ args, response }: ToolContext) { const weatherData = { temperature: 22.5, conditions: 'Partly cloudy', humidity: 65, windSpeed: 12, location: args.location } return response.structured(weatherData) } } ``` -------------------------------- ### Create a new MCP prompt with Ace Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/prompts.md Creates a new prompt file at app/mcp/prompts/my_prompt.ts with a base template. ```bash node ace make:mcp-prompt my_prompt ``` -------------------------------- ### Set @isReadOnly(false) on a tool Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Explicitly set @isReadOnly() to false to indicate the tool modifies state. The example shows a partial UpdateUserTool class with a comment placeholder. ```typescript @isReadOnly(false) export default class UpdateUserTool extends Tool { // ... } ``` -------------------------------- ### Implement completions in a prompt Source: https://github.com/batosai/adonis-mcp/blob/2.x/README.md Add a `complete()` method to a prompt class to provide argument suggestions. The method receives a `CompleteContext` with `args` and `response`; use `response.complete({ values })` to return suggestions. When `args.language` is defined, it returns language options; otherwise returns an empty array. ```typescript import type { PromptContext, CompleteContext } from '@jrmc/adonis-mcp/types/context' import type { BaseSchema } from '@jrmc/adonis-mcp/types/method' import { Prompt } from '@jrmc/adonis-mcp' type Schema = BaseSchema<{ language: { type: "string" } code: { type: "string" } }> export default class CodeReviewPrompt extends Prompt { name = 'code_review' title = 'Code Review' description = 'Review code and provide feedback' async handle({ args, response }: PromptContext) { return [ response.text(`Please review this ${args.language} code:\n\n${args.code}`) ] } async complete({ args, response }: CompleteContext) { // Provide language suggestions when the user types if (args?.language !== undefined) { return response.complete({ values: ['python', 'javascript', 'typescript', 'java', 'go', 'rust'] }) } return response.complete({ values: [] }) } schema() { return { type: "object", properties: { language: { type: "string", description: "Programming language" }, code: { type: "string", description: "Code to review" } }, required: ["language", "code"] } as Schema } } ``` -------------------------------- ### Return text content from a resource handler Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Use `response.text()` to return text-based resources such as documents, JSON, or XML. The example reads a file and returns its content as text. ```typescript async handle({ response }: ResourceContext) { const content = await fs.readFile('path/to/file.txt', 'utf-8') return response.text(content) } ``` -------------------------------- ### Basic JSON Schema definition Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Defines a tool input schema with properties 'page' and 'url', where 'page' is required. Use this as a starting point for simple input validation. ```typescript schema() { return { type: "object", properties: { page: { type: "number", description: "page number for pagination" }, url: { type: "number", description: "per page limit for pagination" } }, required: ["page"] } as Schema } ``` -------------------------------- ### Create a Tool with Schema (TypeScript) Source: https://github.com/batosai/adonis-mcp/blob/2.x/skills/adonis-mcp/SKILL.md Defines a custom MCP tool named 'create_bookmark' that accepts title and url arguments. The schema() method defines the input structure, and the handle method returns a text response. The ToolContext provides args, response, auth, bouncer, and request. ```typescript import type { ToolContext } from '@jrmc/adonis-mcp/types/context' import type { BaseSchema } from '@jrmc/adonis-mcp/types/method' import { Tool } from '@jrmc/adonis-mcp' type Schema = BaseSchema<{ title: { type: "string" } url: { type: "string" } }> export default class AddBookmarkTool extends Tool { name = 'create_bookmark' // required, unique title = 'Create Bookmark' // optional description = 'Create a new bookmark' async handle({ args, response, auth, bouncer, request }: ToolContext) { return response.text(JSON.stringify({ title: args?.title })) } schema() { return { type: "object", properties: { title: { type: "string", description: "Bookmark title" }, url: { type: "string", description: "Bookmark URL" } }, required: ["title", "url"] } as Schema } } ``` -------------------------------- ### JSON-RPC error example for authorization failure Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/authentication.md Shows the expected JSON-RPC error response when authorization fails. The error code is -32600 (InvalidRequest) with message "Access denied". ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32600, "message": "Access denied" } } ``` -------------------------------- ### Add metadata to a resource response with withMeta() Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/resources.md Use `withMeta()` to attach metadata to a response, such as last modified date, source, or cache status. The example shows adding metadata to a text response. ```typescript async handle({ response }: ResourceContext) { const content = await getContent() return response.text(content).withMeta({ lastModified: new Date().toISOString(), source: 'database', cached: false }) } ``` -------------------------------- ### AddBookmarkTool: Create Bookmark Tool Implementation Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Defines a tool named 'create_bookmark' that creates a bookmark record. Uses the Tool base class with a schema for title and url arguments. The handle method creates a Bookmark model instance and returns a JSON response. ```typescript import type { ToolContext } from '@jrmc/adonis-mcp/types/context' import type { BaseSchema } from '@jrmc/adonis-mcp/types/method' import { Tool } from '@jrmc/adonis-mcp' import Bookmark from '#models/bookmark' type Schema = BaseSchema<{ title: { type: "string" } url: { type: "string" } }> export default class AddBookmarkTool extends Tool { name = 'create_bookmark' title = 'Create Bookmark' description = 'Create a new bookmark' async handle({ args, response, auth }: ToolContext) { const bookmark = await Bookmark.create({ title: args?.title, text: args?.url, userId: auth?.user?.id, }) return response.text(JSON.stringify({ bookmark })) } schema() { return { type: "object", properties: { title: { type: "string", description: "Bookmark title" }, url: { type: "string", description: "Bookmark URL" } }, required: ["title", "url"] } as Schema } } ``` -------------------------------- ### Basic handle method with ToolContext Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Shows the core structure of a tool's handle method, accessing validated arguments, using auth and bouncer, and returning a JSON response. ```typescript async handle({ args, response, auth, bouncer }: ToolContext) { // Access validated arguments const result = await SomeModel.query().where('id', args?.id) // Use authentication if available const user = auth.user // Check permissions with Bouncer await bouncer.authorize('viewData') // Return a response return response.text(JSON.stringify({ result })) } ``` -------------------------------- ### Implement complete() for prompt/resource completions Source: https://github.com/batosai/adonis-mcp/blob/2.x/skills/adonis-mcp/SKILL.md Requires `completions: true` in `config/mcp.ts`. Implement `complete()` on the prompt or resource. The method receives a `CompleteContext` and returns `response.complete()` with an array of values, optionally including `hasMore` and `total`. ```typescript import type { CompleteContext } from '@jrmc/adonis-mcp/types/context' async complete({ args, response }: CompleteContext) { if (args?.language !== undefined) { return response.complete({ values: ['typescript', 'python'] }) // + optional hasMore, total } return response.complete({ values: [] }) } ``` -------------------------------- ### Create a Resource (TypeScript) Source: https://github.com/batosai/adonis-mcp/blob/2.x/skills/adonis-mcp/SKILL.md Defines a custom MCP resource named 'user_document' with a URI template 'document:///{id}'. The handle method loads content by ID and returns it as text, optionally setting the size. The ResourceContext provides args and response. ```typescript import type { ResourceContext } from '@jrmc/adonis-mcp/types/context' import { Resource } from '@jrmc/adonis-mcp' type Args = { id: string } export default class UserDocumentResource extends Resource { name = 'user_document' uri = 'document:///{id}' // required, unique; RFC 6570 template mimeType = 'text/plain' title = 'User Document' description = 'Access user documents by ID' async handle({ args, response }: ResourceContext) { const content = await loadDocument(args?.id) this.size = content.length // set size when known return response.text(content) // or response.blob(buffer) for binary } } ``` -------------------------------- ### Using Bouncer for Authorization Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Shows how to check permissions with bouncer.authorize and use policies with bouncer.with(UserPolicy).authorize. ```typescript async handle({ args, bouncer, response }: ToolContext) { // Check a permission await bouncer.authorize(viewUsers) // Or use a policy const user = await User.findOrFail(args?.userId) await bouncer.with(UserPolicy).authorize('view', user) return response.text(JSON.stringify({ user })) } ``` -------------------------------- ### Run a specific test file Source: https://github.com/batosai/adonis-mcp/blob/2.x/tests/README.md Command to run a single test file by specifying its path. ```bash npm test tests/unit/server/context.spec.ts ``` -------------------------------- ### Generate a new MCP tool with Ace Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Run this command to scaffold a new tool file at `app/mcp/tools/my_tool.ts`. ```bash node ace make:mcp-tool my_tool ``` -------------------------------- ### createListPromptsRequest helper usage Source: https://github.com/batosai/adonis-mcp/blob/2.x/tests/README.md Creates a request to list prompts. ```typescript import { createListPromptsRequest } from '../helpers/create_request.js' const request = createListPromptsRequest('cursor123') ``` -------------------------------- ### Using Authentication in handle method Source: https://github.com/batosai/adonis-mcp/blob/2.x/docs/tools.md Demonstrates accessing the authenticated user via auth.user and returning a personalized text response. ```typescript async handle({ args, auth, response }: ToolContext) { const user = auth.user return response.text(`Hello, ${user?.name}`) } ```