# Directory Structure ``` ├── .editorconfig ├── .gitignore ├── license.md ├── package.json ├── pnpm-lock.yaml ├── readme.md ├── src │ ├── config.ts │ ├── directus.ts │ ├── index.ts │ ├── tools │ │ ├── collections.ts │ │ ├── index.ts │ │ ├── items.ts │ │ └── users │ │ └── me.ts │ ├── types │ │ ├── schema.ts │ │ └── tool.ts │ └── utils │ ├── define-tool.ts │ ├── fetch-schema.ts │ ├── to-input-schema.ts │ └── to-mpc-tools.ts └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` 1 | dist 2 | node_modules 3 | .env ``` -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- ``` 1 | root=true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | 9 | [*.{mjs,cjs,js,mts,cts,ts,json,vue,html,scss,css,toml,md}] 10 | indent_style = tab 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | 15 | [*.{yml,yaml}] 16 | indent_style = space ``` -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- ```markdown 1 | > [!WARNING] 2 | > This was an experimental MCP server to test the waters and see what it would allow us to do. We've since released an official Directus MCP server over on https://github.com/directus/mcp 🙂 3 | 4 | --- 5 | 6 | # Directus Model Context Protocol (MCP) Server 7 | 8 | MCP server for use with Directus. Allows your AI tools to connect to and use your Directus API on 9 | your behalf. 10 | 11 | This is an experiment by yours truly (@rijkvanzanten). Any and all PRs are more than welcome :) 12 | 13 | ## Installation 14 | 15 | This MCP server is built to work with NodeJS v22.12 or newer. 16 | 17 | ### Global Installation (Recommended) 18 | 19 | `npm install -g @rijk/directus-mcp-server` 20 | 21 | Then configure Claude AI to use the `npm` package as remote server: 22 | 23 | ```json 24 | { 25 | "mcpServers": { 26 | "directus": { 27 | "command": "directus-mcp-server", 28 | "env": { 29 | "DIRECTUS_URL": "<your Directus instance URL>", 30 | "DIRECTUS_TOKEN": "<your Directus user token>" 31 | } 32 | } 33 | } 34 | } 35 | ``` 36 | 37 | ### Local / Dev Installation 38 | 39 | 1. Clone the repo 40 | 2. `pnpm install && pnpm build` to build the server 41 | 3. Configure Claude AI like above, but pointing it to the `dist` file instead: 42 | 43 | ```json 44 | { 45 | "mcpServers": { 46 | "directus": { 47 | "command": "node", 48 | "args": ["/path/to/directus-mcp-server/dist/index.js"] 49 | } 50 | } 51 | } 52 | ``` 53 | 54 | ## Tools 55 | 56 | ### Read Items 57 | 58 | The `read-items` tool allows you to read items from any Directus collection by providing the collection name as a parameter. 59 | 60 | Parameters: 61 | - `collection`: (required) The name of the collection to read from 62 | - `fields`: (optional) Array of field names to return 63 | - `sort`: (optional) Field to sort by (prefix with `-` for descending order) 64 | - `limit`: (optional) Maximum number of items to return 65 | 66 | Example: 67 | ```json 68 | { 69 | "collection": "articles", 70 | "fields": ["id", "title", "date_published"], 71 | "sort": "-date_published", 72 | "limit": 10 73 | } 74 | ``` 75 | 76 | ### Read Current User 77 | 78 | Get information about the current user. Effectively the `/users/me` endpoint. 79 | 80 | ### Read Collections 81 | 82 | Return what collections/fields are available in the system. Use this tool first to discover available collections before using the `read-items` tool. 83 | 84 | ## License 85 | 86 | MIT 87 | ``` -------------------------------------------------------------------------------- /license.md: -------------------------------------------------------------------------------- ```markdown 1 | Copyright (c) 2025 Rijk van Zanten 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "extends": "@directus/tsconfig/node22", 3 | "compilerOptions": { 4 | "outDir": "dist" 5 | }, 6 | "include": ["src"] 7 | } 8 | ``` -------------------------------------------------------------------------------- /src/types/schema.ts: -------------------------------------------------------------------------------- ```typescript 1 | export type CollectionName = string; 2 | export type FieldName = string; 3 | export type Schema = Record<CollectionName, FieldName[]>; 4 | ``` -------------------------------------------------------------------------------- /src/utils/define-tool.ts: -------------------------------------------------------------------------------- ```typescript 1 | import type { ToolDefinition } from "../types/tool.js"; 2 | 3 | export const defineTool = ( 4 | name: string, 5 | tool: Omit<ToolDefinition, "name">, 6 | ) => ({ name, ...tool }); 7 | ``` -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- ```typescript 1 | import dotenv from 'dotenv'; 2 | import * as z from 'zod'; 3 | 4 | const configSchema = z.object({ 5 | DIRECTUS_URL: z.string(), 6 | DIRECTUS_TOKEN: z.string(), 7 | }); 8 | 9 | export const createConfig = () => { 10 | dotenv.config(); 11 | 12 | return configSchema.parse(process.env); 13 | } 14 | 15 | export type Config = z.infer<typeof configSchema>; 16 | ``` -------------------------------------------------------------------------------- /src/utils/to-mpc-tools.ts: -------------------------------------------------------------------------------- ```typescript 1 | import { zodToJsonSchema } from "zod-to-json-schema"; 2 | import type { ToolDefinition } from "../types/tool.js"; 3 | 4 | export const toMpcTools = (defs: ToolDefinition[]) => { 5 | return defs.map((def) => ({ 6 | name: def.name, 7 | description: def.description, 8 | inputSchema: zodToJsonSchema(def.inputSchema), 9 | })); 10 | }; 11 | ``` -------------------------------------------------------------------------------- /src/tools/collections.ts: -------------------------------------------------------------------------------- ```typescript 1 | import * as z from "zod"; 2 | import { defineTool } from "../utils/define-tool.js"; 3 | 4 | export default defineTool("read-collections", { 5 | description: "Retrieve the schema of the connected Directus instance", 6 | inputSchema: z.object({}), 7 | handler: async (_directus, _args, { schema }) => { 8 | return { content: [{ type: "text", text: JSON.stringify(schema) }] }; 9 | }, 10 | }); 11 | ``` -------------------------------------------------------------------------------- /src/tools/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | import type { ToolDefinition } from "../types/tool.js"; 2 | import collections from "./collections.js"; 3 | import { createGenericReadItemsTool } from "./items.js"; 4 | import usersMe from "./users/me.js"; 5 | 6 | export const getTools = () => { 7 | const genericReadItemsTool = createGenericReadItemsTool(); 8 | const staticTools: ToolDefinition[] = [ 9 | usersMe, 10 | collections, 11 | genericReadItemsTool, 12 | ]; 13 | return staticTools; 14 | }; 15 | ``` -------------------------------------------------------------------------------- /src/types/tool.ts: -------------------------------------------------------------------------------- ```typescript 1 | import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; 2 | import type { ZodType } from "zod"; 3 | import type { Directus } from "../directus.js"; 4 | import type { Schema } from "../types/schema.js"; 5 | 6 | export interface ToolDefinition<Params = any> { 7 | name: string; 8 | description: string; 9 | inputSchema: ZodType<Params>; 10 | handler: ( 11 | directus: Directus, 12 | args: Params, 13 | ctx: { schema: Schema }, 14 | ) => Promise<CallToolResult>; 15 | } 16 | ``` -------------------------------------------------------------------------------- /src/directus.ts: -------------------------------------------------------------------------------- ```typescript 1 | import type { 2 | DirectusClient, 3 | RestClient, 4 | StaticTokenClient, 5 | } from "@directus/sdk"; 6 | import { createDirectus as createSdk, rest, staticToken } from "@directus/sdk"; 7 | import type { Config } from "./config.js"; 8 | 9 | export const createDirectus = (config: Config) => 10 | createSdk(config.DIRECTUS_URL) 11 | .with(staticToken(config.DIRECTUS_TOKEN)) 12 | .with(rest()); 13 | 14 | export type Directus = DirectusClient<any> & 15 | StaticTokenClient<any> & 16 | RestClient<any>; 17 | ``` -------------------------------------------------------------------------------- /src/tools/users/me.ts: -------------------------------------------------------------------------------- ```typescript 1 | import { readMe } from "@directus/sdk"; 2 | import * as z from "zod"; 3 | import { defineTool } from "../../utils/define-tool.js"; 4 | 5 | export default defineTool("users-me", { 6 | description: "Retrieve information about the current user", 7 | inputSchema: z.object({ 8 | fields: z.array(z.string()), 9 | }), 10 | handler: async (directus, { fields }) => { 11 | const me = await directus.request(readMe({ fields })); 12 | 13 | return { content: [{ type: "text", text: JSON.stringify(me) }] }; 14 | }, 15 | }); 16 | ``` -------------------------------------------------------------------------------- /src/utils/fetch-schema.ts: -------------------------------------------------------------------------------- ```typescript 1 | import { readFields } from "@directus/sdk"; 2 | import type { Directus } from "../directus.js"; 3 | import type { Schema } from "../types/schema.js"; 4 | 5 | export async function fetchSchema(directus: Directus): Promise<Schema> { 6 | const fields = (await directus.request(readFields())) as { 7 | collection: string; 8 | field: string; 9 | }[]; 10 | 11 | const schema: Schema = {}; 12 | 13 | for (const field of fields) { 14 | // Ignore system tables 15 | if (field.collection.startsWith("directus_")) continue; 16 | 17 | if (Array.isArray(schema[field.collection])) { 18 | schema[field.collection]!.push(field.field); 19 | } else { 20 | schema[field.collection] = [field.field]; 21 | } 22 | } 23 | 24 | return schema; 25 | } 26 | ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "name": "@rijk/directus-mcp-server", 3 | "version": "0.1.0", 4 | "description": "Model context protocol server for Directus", 5 | "main": "dist/index.js", 6 | "type": "module", 7 | "scripts": { 8 | "build": "tsc --project tsconfig.json", 9 | "dev": "tsc --project tsconfig.json --watch & node --watch dist/index.js", 10 | "start": "node dist/index.js" 11 | }, 12 | "keywords": [ 13 | "ai", 14 | "directus", 15 | "mcp", 16 | "modelcontextprotocol" 17 | ], 18 | "author": "Rijk van Zanten <[email protected]>", 19 | "license": "MIT", 20 | "packageManager": "[email protected]", 21 | "bin": { 22 | "directus-mcp-server": "./dist/index.js" 23 | }, 24 | "prettier": { 25 | "useTabs": true, 26 | "maxLineLength": 100 27 | }, 28 | "dependencies": { 29 | "@directus/sdk": "19.0.1", 30 | "@modelcontextprotocol/sdk": "1.7.0", 31 | "dotenv": "16.4.7", 32 | "zod": "3.24.2", 33 | "zod-to-json-schema": "3.24.4" 34 | }, 35 | "devDependencies": { 36 | "@directus/tsconfig": "3.0.0", 37 | "@types/node": "22.13.10", 38 | "prettier": "3.5.3", 39 | "typescript": "5.8.2" 40 | } 41 | } 42 | ``` -------------------------------------------------------------------------------- /src/utils/to-input-schema.ts: -------------------------------------------------------------------------------- ```typescript 1 | import type { Schema } from "../types/schema.js"; 2 | import type { AnyZodObject, ZodTypeAny, ZodLiteral } from "zod"; 3 | import * as z from "zod"; 4 | 5 | export const toInputSchema = (schema: Schema) => { 6 | const schemas: AnyZodObject[] = []; 7 | 8 | for (const [collection, fields] of Object.entries(schema)) { 9 | let fieldType: ZodTypeAny = z.null(); 10 | 11 | if (fields.length === 1) { 12 | fieldType = z.literal(fields[0]); 13 | } 14 | 15 | if (fields.length > 1) { 16 | fieldType = z.union( 17 | fields.map((f) => z.literal(f)) as [ 18 | ZodLiteral<string>, 19 | ZodLiteral<string>, 20 | ...ZodLiteral<string>[], 21 | ], 22 | ); 23 | } 24 | 25 | schemas.push( 26 | z.object({ 27 | collection: z.literal(collection), 28 | fields: z.array(fieldType), 29 | sort: fieldType, 30 | limit: z.number(), 31 | }), 32 | ); 33 | } 34 | 35 | if (schemas.length === 0) { 36 | return z.object({}); 37 | } 38 | 39 | if (schemas.length === 1) { 40 | return schemas[0] as AnyZodObject; 41 | } 42 | 43 | return z.union(schemas as [AnyZodObject, AnyZodObject, ...AnyZodObject[]]); 44 | }; 45 | ``` -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | #!/usr/bin/env node 2 | 3 | import { Server } from "@modelcontextprotocol/sdk/server/index.js"; 4 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; 5 | import { 6 | type CallToolRequest, 7 | CallToolRequestSchema, 8 | ListToolsRequestSchema, 9 | } from "@modelcontextprotocol/sdk/types.js"; 10 | import { createConfig } from "./config.js"; 11 | import { createDirectus } from "./directus.js"; 12 | import { getTools } from "./tools/index.js"; 13 | import { toMpcTools } from "./utils/to-mpc-tools.js"; 14 | import { fetchSchema } from "./utils/fetch-schema.js"; 15 | 16 | async function main() { 17 | const config = createConfig(); 18 | const directus = createDirectus(config); 19 | const schema = await fetchSchema(directus); 20 | const tools = getTools(); 21 | 22 | const server = new Server( 23 | { 24 | name: "Directus MCP Server", 25 | version: "0.0.1", 26 | }, 27 | { 28 | capabilities: { 29 | tools: {}, 30 | }, 31 | }, 32 | ); 33 | 34 | // server.sendLoggingMessage({ 35 | // level: "info", 36 | // data: "Server started successfully", 37 | // }); 38 | 39 | server.setRequestHandler( 40 | CallToolRequestSchema, 41 | async (request: CallToolRequest) => { 42 | // server.sendLoggingMessage({ 43 | // level: "debug", 44 | // data: `Received CallToolRequests: ${request}`, 45 | // }); 46 | 47 | try { 48 | const tool = tools.find((definition) => { 49 | return definition.name === request.params.name; 50 | }); 51 | 52 | if (!tool) { 53 | throw new Error(`Unknown tool: ${request.params.name}`); 54 | } 55 | 56 | const { inputSchema, handler } = tool; 57 | 58 | const args = inputSchema.parse(request.params.arguments); 59 | 60 | return await handler(directus, args, { schema }); 61 | } catch (error) { 62 | console.error("Error executing tool:", error); 63 | 64 | return { 65 | content: [ 66 | { 67 | type: "text", 68 | text: JSON.stringify(error), 69 | }, 70 | ], 71 | }; 72 | } 73 | }, 74 | ); 75 | 76 | server.setRequestHandler(ListToolsRequestSchema, async () => { 77 | // server.sendLoggingMessage({ 78 | // level: "debug", 79 | // data: "Received ListToolsRequest", 80 | // }); 81 | 82 | return { tools: toMpcTools(tools) }; 83 | }); 84 | 85 | const transport = new StdioServerTransport(); 86 | 87 | // server.sendLoggingMessage({ 88 | // level: "debug", 89 | // data: "Connecting server to transport...", 90 | // }); 91 | 92 | await server.connect(transport); 93 | 94 | // server.sendLoggingMessage({ 95 | // level: "debug", 96 | // data: "Directus MCP Server running on stdio", 97 | // }); 98 | } 99 | 100 | main().catch((error) => { 101 | console.error("Fatal error in main():", error); 102 | process.exit(1); 103 | }); 104 | ``` -------------------------------------------------------------------------------- /src/tools/items.ts: -------------------------------------------------------------------------------- ```typescript 1 | import { readItems } from "@directus/sdk"; 2 | import * as z from "zod"; 3 | import type { Schema } from "../types/schema.js"; 4 | import { defineTool } from "../utils/define-tool.js"; 5 | 6 | export const createGenericReadItemsTool = () => { 7 | return defineTool("read-items", { 8 | description: 9 | "Read items from any collection. Fields and sort options are validated against the schema.", 10 | inputSchema: z.object({ 11 | collection: z 12 | .string() 13 | .describe("The name of the collection to read from"), 14 | fields: z.array(z.string()).optional().describe("Fields to return"), 15 | sort: z 16 | .string() 17 | .optional() 18 | .describe("Field to sort by (prefix with - for descending)"), 19 | limit: z 20 | .number() 21 | .optional() 22 | .describe("Maximum number of items to return"), 23 | }), 24 | handler: async (directus, query, { schema: contextSchema }) => { 25 | const { collection, fields, sort, ...otherParams } = query; 26 | 27 | try { 28 | if (!contextSchema[collection]) { 29 | throw new Error( 30 | `Collection "${collection}" not found. Use read-collections tool first.`, 31 | ); 32 | } 33 | 34 | const availableFields = contextSchema[collection] || []; 35 | 36 | if (fields && fields.length > 0) { 37 | const invalidFields = fields.filter( 38 | (field: string) => !availableFields.includes(field), 39 | ); 40 | if (invalidFields.length > 0) { 41 | throw new Error( 42 | `Invalid fields for "${collection}": ${invalidFields.join(", ")}`, 43 | ); 44 | } 45 | } 46 | 47 | if (sort) { 48 | const sortField = sort.startsWith("-") ? sort.substring(1) : sort; 49 | if (!availableFields.includes(sortField)) { 50 | throw new Error( 51 | `Invalid sort field "${sortField}" for collection "${collection}"`, 52 | ); 53 | } 54 | } 55 | 56 | const params: Record<string, any> = { ...otherParams }; 57 | 58 | if (fields && fields.length > 0) { 59 | params["fields"] = fields; 60 | } 61 | 62 | if (sort) { 63 | params["sort"] = sort; 64 | } 65 | 66 | const items = await directus.request(readItems(collection, params)); 67 | return { content: [{ type: "text", text: JSON.stringify(items) }] }; 68 | } catch (error: any) { 69 | return { 70 | content: [ 71 | { 72 | type: "text", 73 | text: JSON.stringify({ 74 | error: `Error: ${error?.message || "Unknown error"}`, 75 | }), 76 | }, 77 | ], 78 | }; 79 | } 80 | }, 81 | }); 82 | }; 83 | 84 | export const getCollectionSchema = (schema: Schema, collection: string) => { 85 | const fields = schema[collection] || []; 86 | const description = `Collection "${collection}" has these fields: ${fields.join(", ")}`; 87 | return { fields, description }; 88 | }; 89 | ```