Ajout d'outils MCP

VérifiéSûr

Guide pour ajouter de nouveaux outils MCP avec des motifs cohérents pour les schémas, définitions d'outils, mises à jour du registre et intégration Better Auth.

Spar Skills Guide Bot
DeveloppementIntermédiaire
26/07/2026
Claude CodeCursorCodex
#mcp#zod#typescript#code-generation#api-design

Recommandé pour

Synthèse automatique

Guide pas à pas pour ajouter un nouveau domaine d'outils MCP au codebase Studio, avec schémas Zod, defineTool, contrôle d'accès et intégration Better Auth.

Points forts

  • Impose une structure de fichiers reproductible (schema.ts, create.ts, list.ts, update.ts, delete.ts, index.ts).
  • Rend explicite la séquence d'autorisation : requireAuth, requireOrganization, ctx.access.check(), getUserId.
  • Montre les deux voies d'intégration possibles : ctx.boundAuth pour Better Auth et ctx.storage pour un stockage maison.
  • Chaque outil dispose de schémas Zod d'entrée et de sortie, ce qui limite les dérives de contrat.

Limites

  • Fortement couplé au codebase interne Studio : les chemins et les helpers ne sont pas transposables tels quels.
  • Le document fourni est tronqué : l'export barrel final et l'étape d'enregistrement dans le registre MCP ne sont pas montrés.
  • Aucune indication sur les tests ou la validation des outils nouvellement créés.
Quand l'utiliser

À utiliser lorsqu'on ajoute un nouveau domaine d'outils MCP de type CRUD (create/list/update/delete) à l'API Studio.

Quand l'éviter

À éviter sur un autre codebase ou pour un outil qui ne suit pas le schéma create/list/update/delete standard.

Analyse de sécurité

Sûr
Score qualité85/100

This is a documentation/guide skill describing patterns for adding MCP tools. It contains code snippets for Zod schemas, tool definitions, auth checks, and registry updates, but no shell commands, destructive actions, exfiltration, obfuscation, or disabling of safety features. The instructions are purely educational and implementation-focused.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Scaffold a new webhooks tool domain
Add a new `webhooks` MCP tool domain to apps/api/src/tools, with create, list, update and delete tools that follow the existing schema/defineTool/barrel-export pattern.
Write only the Zod schemas
Create apps/api/src/tools/secrets/schema.ts with the entity schema plus create, list, update and delete input/output Zod schemas, matching the conventions used by the existing tools.
Audit a tool's auth checks
Review my new apiKeys create tool: it should call requireAuth, requireOrganization and ctx.access.check() before touching ctx.boundAuth, and return the created item in the defined output schema.

name: add-mcp-tools description: Guide for adding new MCP tools with consistent patterns for schemas, tool definitions, registry updates, and Better Auth integration

Adding New MCP Tools to Studio

This guide documents the pattern for adding new MCP tools to Studio codebase. Follow this checklist to ensure consistency with existing tools.

Overview

MCP tools are exposed via the Model Context Protocol and allow programmatic management of resources. Each tool follows a consistent pattern with:

  • Zod schemas for input/output validation
  • defineTool for automatic tracing, metrics, and audit logging
  • Access control via ctx.access.check()
  • Better Auth integration via ctx.boundAuth

File Structure

When adding a new domain of tools (e.g., apiKeys, webhooks, secrets), create the following structure:

apps/api/src/tools/<domain>/
├── schema.ts     # Zod schemas for entities and operations
├── create.ts     # <DOMAIN>_CREATE tool
├── list.ts       # <DOMAIN>_LIST tool
├── update.ts     # <DOMAIN>_UPDATE tool  
├── delete.ts     # <DOMAIN>_DELETE tool
└── index.ts      # Barrel export

Step-by-Step Checklist

1. Create Schema File (schema.ts)

Define Zod schemas for:

  • Entity schema: The resource returned in list/get operations
  • Create input/output schemas: Input for creation, output includes created entity
  • Update input/output schemas: Partial updates
  • Delete input/output schemas: ID input, success confirmation output
// apps/api/src/tools/<domain>/schema.ts
import { z } from "zod";

// Entity schema (what's returned in list operations)
export const MyEntitySchema = z.object({
  id: z.string(),
  name: z.string(),
  // ... other fields
  createdAt: z.union([z.string(), z.date()]),
});

export type MyEntity = z.infer<typeof MyEntitySchema>;

// Create schemas
export const MyCreateInputSchema = z.object({
  name: z.string().min(1).max(255),
  // ... other fields
});

export const MyCreateOutputSchema = z.object({
  item: MyEntitySchema,
});

// List schemas
export const MyListInputSchema = z.object({
  // pagination, filters, etc.
});

export const MyListOutputSchema = z.object({
  items: z.array(MyEntitySchema),
});

// Update schemas
export const MyUpdateInputSchema = z.object({
  id: z.string(),
  // ... partial fields
});

export const MyUpdateOutputSchema = z.object({
  item: MyEntitySchema,
});

// Delete schemas
export const MyDeleteInputSchema = z.object({
  id: z.string(),
});

export const MyDeleteOutputSchema = z.object({
  success: z.boolean(),
  id: z.string(),
});

2. Create Tool Files

Each tool file follows this pattern:

// apps/api/src/tools/<domain>/create.ts
import { defineTool } from "../../core/define-tool";
import { getUserId, requireAuth, requireOrganization } from "../../core/studio-context";
import { MyCreateInputSchema, MyCreateOutputSchema } from "./schema";

export const MY_DOMAIN_CREATE = defineTool({
  name: "MY_DOMAIN_CREATE",
  description: "Create a new resource",

  inputSchema: MyCreateInputSchema,
  outputSchema: MyCreateOutputSchema,

  handler: async (input, ctx) => {
    // 1. Require authentication
    requireAuth(ctx);
    
    // 2. Require organization (if org-scoped)
    const organization = requireOrganization(ctx);
    
    // 3. Check authorization
    await ctx.access.check();
    
    // 4. Get user ID
    const userId = getUserId(ctx);
    if (!userId) {
      throw new Error("User ID required");
    }
    
    // 5. Perform operation
    // Option A: Use ctx.boundAuth for Better Auth operations
    const result = await ctx.boundAuth.myDomain.create({ ... });
    
    // Option B: Use ctx.storage for custom storage operations
    const result = await ctx.storage.myDomain.create({ ... });
    
    // 6. Return result
    return { item: result };
  },
});

3. Create Barrel Export (index.ts)

// apps/api/src/tools/<domain>/index.ts
export { MY_DOMAIN_CREATE } from "./create";
export { MY_DOMAIN_LIST } from "./list";
export { MY_DOMAIN_UPDATE } from "./update";
export { MY_DOMAIN_DELETE } from "./delete";

// Export schemas for external use
export * from "./schema";

4. Update Tool Registry (registry.ts)

Add tool names and metadata:

// apps/api/src/tools/registry.ts

// 1. Add to ToolCategory type (if new category)
export type ToolCategory = "Organizations" | "Connections" | "My Domain";

// 2. Add to ALL_TOOL_NAMES array
const ALL_TOOL_NAMES = [
  // ... existing tools
  "MY_DOMAIN_CREATE",
  "MY_DOMAIN_LIST",
  "MY_DOMAIN_UPDATE",
  "MY_DOMAIN_DELETE",
] as const;

// 3. Add to MANAGEMENT_TOOLS array
export const MANAGEMENT_TOOLS: ToolMetadata[] = [
  // ... existing tools
  {
    name: "MY_DOMAIN_CREATE",
    description: "Create resource",
    category: "My Domain",
  },
  {
    name: "MY_DOMAIN_LIST",
    description: "List resources",
    category: "My Domain",
  },
  {
    name: "MY_DOMAIN_UPDATE",
    description: "Update resource",
    category: "My Domain",
  },
  {
    name: "MY_DOMAIN_DELETE",
    description: "Delete resource",
    category: "My Domain",
    dangerous: true,
  },
];

// 4. Add to TOOL_LABELS
const TOOL_LABELS: Record<ToolName, string> = {
  // ... existing labels
  MY_DOMAIN_CREATE: "Create resource",
  MY_DOMAIN_LIST: "List resources",
  MY_DOMAIN_UPDATE: "Update resource",
  MY_DOMAIN_DELETE: "Delete resource",
};

// 5. Update getToolsByCategory if new category
export function getToolsByCategory() {
  const grouped: Record<string, ToolMetadata[]> = {
    Organizations: [],
    Connections: [],
    "My Domain": [], // Add new category
  };
  // ...
}

5. Register Tools (tools/index.ts)

// apps/api/src/tools/index.ts
import * as MyDomainTools from "./myDomain";

export { MyDomainTools };

export const ALL_TOOLS = [
  // ... existing tools
  MyDomainTools.MY_DOMAIN_CREATE,
  MyDomainTools.MY_DOMAIN_LIST,
  MyDomainTools.MY_DOMAIN_UPDATE,
  MyDomainTools.MY_DOMAIN_DELETE,
] as const satisfies { name: ToolName }[];

6. Add to Default Permissions (if needed)

// apps/api/src/auth/index.ts
apiKey({
  permissions: {
    defaultPermissions: {
      self: [
        // ... existing permissions
        "MY_DOMAIN_LIST", // Read access by default
        // Note: CREATE, UPDATE, DELETE usually NOT default
      ],
    },
  },
}),

7. Add Better Auth Integration (if wrapping Better Auth API)

If your tools wrap Better Auth APIs, you need to:

a. Add types to studio-context.ts:

// apps/api/src/core/studio-context.ts

// Add return types
export type MyDomainCreateResult = Awaited<
  ReturnType<BetterAuthApi["createMyDomain"]>
>;
// ... other types

// Add to BoundAuthClient interface
export interface BoundAuthClient {
  // ... existing methods
  
  myDomain: {
    create(data: { ... }): Promise<MyDomainCreateResult>;
    list(): Promise<MyDomainListResult>;
    update(data: { ... }): Promise<MyDomainUpdateResult>;
    delete(id: string): Promise<void>;
  };
}

b. Implement in context-factory.ts:

// apps/api/src/core/context-factory.ts
function createBoundAuthClient(ctx: AuthContext): BoundAuthClient {
  return {
    // ... existing implementations
    
    myDomain: {
      create: async (data) => {
        return auth.api.createMyDomain({ headers, body: data });
      },
      list: async () => {
        return auth.api.listMyDomain({ headers });
      },
      update: async (data) => {
        return auth.api.updateMyDomain({ headers, body: data });
      },
      delete: async (id) => {
        await auth.api.deleteMyDomain({ headers, body: { id } });
      },
    },
  };
}

8. Document in Spec

Add documentation to apps/api/spec/001.md:

#### My Domain Management

Description of what this domain manages.

**MY_DOMAIN_CREATE**

\`\`\`typescript
// Create example
POST /mcp/tools/MY_DOMAIN_CREATE
{ "name": "Example" }
// Response
{ "item": { "id": "...", "name": "Example", ... } }
\`\`\`

// ... other tools

Key Patterns to Follow

Authentication & Authorization

// Always in this order:
requireAuth(ctx);                    // 1. Must be authenticated
const org = requireOrganization(ctx); // 2. Must have org context (if org-scoped)
await ctx.access.check();            // 3. Must have permission for this tool

Error Handling

// Throw descriptive errors
if (!result) {
  throw new Error(`Resource not found: ${id}`);
}

if (result.organizationId !== organization.id) {
  throw new Error("Resource not found in organization");
}

Sensitive Data

For sensitive data (like API key values):

// Only return sensitive data at creation time
export const CreateOutputSchema = z.object({
  id: z.string(),
  secretValue: z.string(), // Only here!
});

// Never return in list/get
export const EntitySchema = z.object({
  id: z.string(),
  // NO secretValue field
});

Testing

Create test files alongside tool files:

apps/api/src/tools/<domain>/
├── create.test.ts
├── list.test.ts
├── update.test.ts
└── delete.test.ts

Use the existing test patterns from apps/api/src/tools/connection/ as reference.

Common Mistakes to Avoid

  1. Forgetting await ctx.access.check() - Always check authorization
  2. Missing tool registration - Update both registry.ts AND tools/index.ts
  3. Inconsistent naming - Use DOMAIN_ACTION pattern (e.g., API_KEY_CREATE)
  4. Missing default permissions - Add to auth/index.ts if users should have access by default
  5. Exposing sensitive data - Only return secrets at creation time
  6. Missing organization check - Use requireOrganization(ctx) for org-scoped resources

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/adding-mcp-tools-ms1aw5y8' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/adding-mcp-tools-ms1aw5y8/download' --output '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md.part' && mv '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md.part' '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md' && test -s '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/add-mcp-tools' && cp -R '.skill-downloads/adding-mcp-tools-ms1aw5y8' '.claude/skills/add-mcp-tools'

Cursor
test -f '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md' && test -s '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/add-mcp-tools' && cp -R '.skill-downloads/adding-mcp-tools-ms1aw5y8' '.cursor/skills/add-mcp-tools'

Codex
test -f '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md' && test -s '.skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/add-mcp-tools' && cp -R '.skill-downloads/adding-mcp-tools-ms1aw5y8' '.agents/skills/add-mcp-tools'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/adding-mcp-tools-ms1aw5y8'

openskills read 'adding-mcp-tools-ms1aw5y8'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/adding-mcp-tools-ms1aw5y8/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires