#
tokens: 4118/50000 19/19 files
lines: off (toggle) GitHub
raw markdown copy
# 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:
--------------------------------------------------------------------------------

```
dist
node_modules
.env
```

--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------

```
root=true

[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true

[*.{mjs,cjs,js,mts,cts,ts,json,vue,html,scss,css,toml,md}]
indent_style = tab

[*.md]
trim_trailing_whitespace = false

[*.{yml,yaml}]
indent_style = space
```

--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------

```markdown
> [!WARNING]
> 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 🙂

---

# Directus Model Context Protocol (MCP) Server

MCP server for use with Directus. Allows your AI tools to connect to and use your Directus API on
your behalf.

This is an experiment by yours truly (@rijkvanzanten). Any and all PRs are more than welcome :)

## Installation

This MCP server is built to work with NodeJS v22.12 or newer.

### Global Installation (Recommended)

`npm install -g @rijk/directus-mcp-server`

Then configure Claude AI to use the `npm` package as remote server:

```json
{
	"mcpServers": {
		"directus": {
			"command": "directus-mcp-server",
			"env": {
				"DIRECTUS_URL": "<your Directus instance URL>",
				"DIRECTUS_TOKEN": "<your Directus user token>"
			}
		}
	}
}
```

### Local / Dev Installation

1. Clone the repo
2. `pnpm install && pnpm build` to build the server
3. Configure Claude AI like above, but pointing it to the `dist` file instead:

```json
{
	"mcpServers": {
		"directus": {
			"command": "node",
			"args": ["/path/to/directus-mcp-server/dist/index.js"]
		}
	}
}
```

## Tools

### Read Items

The `read-items` tool allows you to read items from any Directus collection by providing the collection name as a parameter.

Parameters:
- `collection`: (required) The name of the collection to read from
- `fields`: (optional) Array of field names to return
- `sort`: (optional) Field to sort by (prefix with `-` for descending order)
- `limit`: (optional) Maximum number of items to return

Example:
```json
{
  "collection": "articles",
  "fields": ["id", "title", "date_published"],
  "sort": "-date_published",
  "limit": 10
}
```

### Read Current User

Get information about the current user. Effectively the `/users/me` endpoint.

### Read Collections

Return what collections/fields are available in the system. Use this tool first to discover available collections before using the `read-items` tool.

## License

MIT

```

--------------------------------------------------------------------------------
/license.md:
--------------------------------------------------------------------------------

```markdown
Copyright (c) 2025 Rijk van Zanten

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.

```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
	"extends": "@directus/tsconfig/node22",
	"compilerOptions": {
		"outDir": "dist"
	},
	"include": ["src"]
}

```

--------------------------------------------------------------------------------
/src/types/schema.ts:
--------------------------------------------------------------------------------

```typescript
export type CollectionName = string;
export type FieldName = string;
export type Schema = Record<CollectionName, FieldName[]>;

```

--------------------------------------------------------------------------------
/src/utils/define-tool.ts:
--------------------------------------------------------------------------------

```typescript
import type { ToolDefinition } from "../types/tool.js";

export const defineTool = (
	name: string,
	tool: Omit<ToolDefinition, "name">,
) => ({ name, ...tool });

```

--------------------------------------------------------------------------------
/src/config.ts:
--------------------------------------------------------------------------------

```typescript
import dotenv from 'dotenv';
import * as z from 'zod';

const configSchema = z.object({
	DIRECTUS_URL: z.string(),
	DIRECTUS_TOKEN: z.string(),
});

export const createConfig = () => {
	dotenv.config();

	return configSchema.parse(process.env);
}

export type Config = z.infer<typeof configSchema>;

```

--------------------------------------------------------------------------------
/src/utils/to-mpc-tools.ts:
--------------------------------------------------------------------------------

```typescript
import { zodToJsonSchema } from "zod-to-json-schema";
import type { ToolDefinition } from "../types/tool.js";

export const toMpcTools = (defs: ToolDefinition[]) => {
	return defs.map((def) => ({
		name: def.name,
		description: def.description,
		inputSchema: zodToJsonSchema(def.inputSchema),
	}));
};

```

--------------------------------------------------------------------------------
/src/tools/collections.ts:
--------------------------------------------------------------------------------

```typescript
import * as z from "zod";
import { defineTool } from "../utils/define-tool.js";

export default defineTool("read-collections", {
	description: "Retrieve the schema of the connected Directus instance",
	inputSchema: z.object({}),
	handler: async (_directus, _args, { schema }) => {
		return { content: [{ type: "text", text: JSON.stringify(schema) }] };
	},
});

```

--------------------------------------------------------------------------------
/src/tools/index.ts:
--------------------------------------------------------------------------------

```typescript
import type { ToolDefinition } from "../types/tool.js";
import collections from "./collections.js";
import { createGenericReadItemsTool } from "./items.js";
import usersMe from "./users/me.js";

export const getTools = () => {
	const genericReadItemsTool = createGenericReadItemsTool();
	const staticTools: ToolDefinition[] = [
		usersMe,
		collections,
		genericReadItemsTool,
	];
	return staticTools;
};

```

--------------------------------------------------------------------------------
/src/types/tool.ts:
--------------------------------------------------------------------------------

```typescript
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import type { ZodType } from "zod";
import type { Directus } from "../directus.js";
import type { Schema } from "../types/schema.js";

export interface ToolDefinition<Params = any> {
	name: string;
	description: string;
	inputSchema: ZodType<Params>;
	handler: (
		directus: Directus,
		args: Params,
		ctx: { schema: Schema },
	) => Promise<CallToolResult>;
}

```

--------------------------------------------------------------------------------
/src/directus.ts:
--------------------------------------------------------------------------------

```typescript
import type {
	DirectusClient,
	RestClient,
	StaticTokenClient,
} from "@directus/sdk";
import { createDirectus as createSdk, rest, staticToken } from "@directus/sdk";
import type { Config } from "./config.js";

export const createDirectus = (config: Config) =>
	createSdk(config.DIRECTUS_URL)
		.with(staticToken(config.DIRECTUS_TOKEN))
		.with(rest());

export type Directus = DirectusClient<any> &
	StaticTokenClient<any> &
	RestClient<any>;

```

--------------------------------------------------------------------------------
/src/tools/users/me.ts:
--------------------------------------------------------------------------------

```typescript
import { readMe } from "@directus/sdk";
import * as z from "zod";
import { defineTool } from "../../utils/define-tool.js";

export default defineTool("users-me", {
	description: "Retrieve information about the current user",
	inputSchema: z.object({
		fields: z.array(z.string()),
	}),
	handler: async (directus, { fields }) => {
		const me = await directus.request(readMe({ fields }));

		return { content: [{ type: "text", text: JSON.stringify(me) }] };
	},
});

```

--------------------------------------------------------------------------------
/src/utils/fetch-schema.ts:
--------------------------------------------------------------------------------

```typescript
import { readFields } from "@directus/sdk";
import type { Directus } from "../directus.js";
import type { Schema } from "../types/schema.js";

export async function fetchSchema(directus: Directus): Promise<Schema> {
	const fields = (await directus.request(readFields())) as {
		collection: string;
		field: string;
	}[];

	const schema: Schema = {};

	for (const field of fields) {
		// Ignore system tables
		if (field.collection.startsWith("directus_")) continue;

		if (Array.isArray(schema[field.collection])) {
			schema[field.collection]!.push(field.field);
		} else {
			schema[field.collection] = [field.field];
		}
	}

	return schema;
}

```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
	"name": "@rijk/directus-mcp-server",
	"version": "0.1.0",
	"description": "Model context protocol server for Directus",
	"main": "dist/index.js",
	"type": "module",
	"scripts": {
		"build": "tsc --project tsconfig.json",
		"dev": "tsc --project tsconfig.json --watch & node --watch dist/index.js",
		"start": "node dist/index.js"
	},
	"keywords": [
		"ai",
		"directus",
		"mcp",
		"modelcontextprotocol"
	],
	"author": "Rijk van Zanten <[email protected]>",
	"license": "MIT",
	"packageManager": "[email protected]",
	"bin": {
		"directus-mcp-server": "./dist/index.js"
	},
	"prettier": {
		"useTabs": true,
		"maxLineLength": 100
	},
	"dependencies": {
		"@directus/sdk": "19.0.1",
		"@modelcontextprotocol/sdk": "1.7.0",
		"dotenv": "16.4.7",
		"zod": "3.24.2",
		"zod-to-json-schema": "3.24.4"
	},
	"devDependencies": {
		"@directus/tsconfig": "3.0.0",
		"@types/node": "22.13.10",
		"prettier": "3.5.3",
		"typescript": "5.8.2"
	}
}

```

--------------------------------------------------------------------------------
/src/utils/to-input-schema.ts:
--------------------------------------------------------------------------------

```typescript
import type { Schema } from "../types/schema.js";
import type { AnyZodObject, ZodTypeAny, ZodLiteral } from "zod";
import * as z from "zod";

export const toInputSchema = (schema: Schema) => {
	const schemas: AnyZodObject[] = [];

	for (const [collection, fields] of Object.entries(schema)) {
		let fieldType: ZodTypeAny = z.null();

		if (fields.length === 1) {
			fieldType = z.literal(fields[0]);
		}

		if (fields.length > 1) {
			fieldType = z.union(
				fields.map((f) => z.literal(f)) as [
					ZodLiteral<string>,
					ZodLiteral<string>,
					...ZodLiteral<string>[],
				],
			);
		}

		schemas.push(
			z.object({
				collection: z.literal(collection),
				fields: z.array(fieldType),
				sort: fieldType,
				limit: z.number(),
			}),
		);
	}

	if (schemas.length === 0) {
		return z.object({});
	}

	if (schemas.length === 1) {
		return schemas[0] as AnyZodObject;
	}

	return z.union(schemas as [AnyZodObject, AnyZodObject, ...AnyZodObject[]]);
};

```

--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------

```typescript
#!/usr/bin/env node

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
	type CallToolRequest,
	CallToolRequestSchema,
	ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { createConfig } from "./config.js";
import { createDirectus } from "./directus.js";
import { getTools } from "./tools/index.js";
import { toMpcTools } from "./utils/to-mpc-tools.js";
import { fetchSchema } from "./utils/fetch-schema.js";

async function main() {
	const config = createConfig();
	const directus = createDirectus(config);
	const schema = await fetchSchema(directus);
	const tools = getTools();

	const server = new Server(
		{
			name: "Directus MCP Server",
			version: "0.0.1",
		},
		{
			capabilities: {
				tools: {},
			},
		},
	);

	// server.sendLoggingMessage({
	// 	level: "info",
	// 	data: "Server started successfully",
	// });

	server.setRequestHandler(
		CallToolRequestSchema,
		async (request: CallToolRequest) => {
			// server.sendLoggingMessage({
			// 	level: "debug",
			// 	data: `Received CallToolRequests: ${request}`,
			// });

			try {
				const tool = tools.find((definition) => {
					return definition.name === request.params.name;
				});

				if (!tool) {
					throw new Error(`Unknown tool: ${request.params.name}`);
				}

				const { inputSchema, handler } = tool;

				const args = inputSchema.parse(request.params.arguments);

				return await handler(directus, args, { schema });
			} catch (error) {
				console.error("Error executing tool:", error);

				return {
					content: [
						{
							type: "text",
							text: JSON.stringify(error),
						},
					],
				};
			}
		},
	);

	server.setRequestHandler(ListToolsRequestSchema, async () => {
		// server.sendLoggingMessage({
		// 	level: "debug",
		// 	data: "Received ListToolsRequest",
		// });

		return { tools: toMpcTools(tools) };
	});

	const transport = new StdioServerTransport();

	// server.sendLoggingMessage({
	// 	level: "debug",
	// 	data: "Connecting server to transport...",
	// });

	await server.connect(transport);

	// server.sendLoggingMessage({
	// 	level: "debug",
	// 	data: "Directus MCP Server running on stdio",
	// });
}

main().catch((error) => {
	console.error("Fatal error in main():", error);
	process.exit(1);
});

```

--------------------------------------------------------------------------------
/src/tools/items.ts:
--------------------------------------------------------------------------------

```typescript
import { readItems } from "@directus/sdk";
import * as z from "zod";
import type { Schema } from "../types/schema.js";
import { defineTool } from "../utils/define-tool.js";

export const createGenericReadItemsTool = () => {
	return defineTool("read-items", {
		description:
			"Read items from any collection. Fields and sort options are validated against the schema.",
		inputSchema: z.object({
			collection: z
				.string()
				.describe("The name of the collection to read from"),
			fields: z.array(z.string()).optional().describe("Fields to return"),
			sort: z
				.string()
				.optional()
				.describe("Field to sort by (prefix with - for descending)"),
			limit: z
				.number()
				.optional()
				.describe("Maximum number of items to return"),
		}),
		handler: async (directus, query, { schema: contextSchema }) => {
			const { collection, fields, sort, ...otherParams } = query;

			try {
				if (!contextSchema[collection]) {
					throw new Error(
						`Collection "${collection}" not found. Use read-collections tool first.`,
					);
				}

				const availableFields = contextSchema[collection] || [];

				if (fields && fields.length > 0) {
					const invalidFields = fields.filter(
						(field: string) => !availableFields.includes(field),
					);
					if (invalidFields.length > 0) {
						throw new Error(
							`Invalid fields for "${collection}": ${invalidFields.join(", ")}`,
						);
					}
				}

				if (sort) {
					const sortField = sort.startsWith("-") ? sort.substring(1) : sort;
					if (!availableFields.includes(sortField)) {
						throw new Error(
							`Invalid sort field "${sortField}" for collection "${collection}"`,
						);
					}
				}

				const params: Record<string, any> = { ...otherParams };

				if (fields && fields.length > 0) {
					params["fields"] = fields;
				}

				if (sort) {
					params["sort"] = sort;
				}

				const items = await directus.request(readItems(collection, params));
				return { content: [{ type: "text", text: JSON.stringify(items) }] };
			} catch (error: any) {
				return {
					content: [
						{
							type: "text",
							text: JSON.stringify({
								error: `Error: ${error?.message || "Unknown error"}`,
							}),
						},
					],
				};
			}
		},
	});
};

export const getCollectionSchema = (schema: Schema, collection: string) => {
	const fields = schema[collection] || [];
	const description = `Collection "${collection}" has these fields: ${fields.join(", ")}`;
	return { fields, description };
};

```