Skip to main content
Glama

generate-api-routes

Generate API route handlers for Next.js, Express, Fastify, or NestJS frameworks that integrate with the Kalendis scheduling backend to manage users, availability, and bookings.

Instructions

Generate API route handlers for Next.js or Express that use the Kalendis backend client

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
frameworkYesTarget framework
typesImportPathNoImport path for types file (optional, defaults to "@/lib/types" for Next.js)

Implementation Reference

  • src/server.ts:67-85 (registration)
    Registers the generate-api-routes tool with name, description, and input schema in the TOOLS array used by the MCP server.
    {
      name: 'generate-api-routes',
      description: 'Generate API route handlers for Next.js or Express that use the Kalendis backend client',
      inputSchema: {
        type: 'object',
        properties: {
          framework: {
            type: 'string',
            enum: ['nextjs', 'express', 'fastify', 'nestjs'],
            description: 'Target framework',
          },
          typesImportPath: {
            type: 'string',
            description: 'Import path for types file (optional, defaults to "@/lib/types" for Next.js)',
          },
        },
        required: ['framework'],
      },
    },
  • Input schema defining the expected arguments: framework (required, enum) and optional typesImportPath.
    inputSchema: {
      type: 'object',
      properties: {
        framework: {
          type: 'string',
          enum: ['nextjs', 'express', 'fastify', 'nestjs'],
          description: 'Target framework',
        },
        typesImportPath: {
          type: 'string',
          description: 'Import path for types file (optional, defaults to "@/lib/types" for Next.js)',
        },
      },
      required: ['framework'],
    },
  • Main handler logic for the tool: validates framework input and delegates to framework-specific generator functions (generateNextjsRoutes, generateExpressRoutes, etc.), formats output as text content.
    case 'generate-api-routes': {
      if (
        !args?.framework ||
        typeof args.framework !== 'string' ||
        !['nextjs', 'express', 'fastify', 'nestjs'].includes(args.framework)
      ) {
        throw new Error('Valid framework is required (nextjs, express, fastify, or nestjs)');
      }
    
      let code: string;
      if (args.framework === 'nextjs') {
        const routes = generateNextjsRoutes(args.typesImportPath as string | undefined);
        code = Object.entries(routes)
          .map(([path, content]) => `// File: ${path}\n${content}`)
          .join('\n\n// ========================================\n\n');
      } else if (args.framework === 'express') {
        code = generateExpressRoutes();
      } else if (args.framework === 'fastify') {
        code = generateFastifyRoutes();
      } else if (args.framework === 'nestjs') {
        const files = generateNestJSModule(args.typesImportPath as string | undefined);
        code = Object.entries(files)
          .map(([path, content]) => `// File: ${path}\n${content}`)
          .join('\n\n// ========================================\n\n');
      } else {
        throw new Error(`Unsupported framework: ${args.framework}`);
      }
    
      return {
        content: [
          {
            type: 'text',
            text: code,
          },
        ],
      };
    }
  • Helper function generates Next.js app router API route files for users, bookings, availability, and account endpoints using the Kalendis backend client.
    export function generateNextjsRoutes(typesPath: string = '@/lib/types'): Record<string, string> {
      const files: Record<string, string> = {};
    
      files['app/api/users/route.ts'] = `import { NextRequest, NextResponse } from 'next/server';
    import KalendisClient from '@/lib/kalendisClient';
    
    const kalendisClient = new KalendisClient({ 
      apiKey: process.env.KALENDIS_API_KEY! 
    });
    
    export async function GET() {
      try {
        const users = await kalendisClient.getUsersByAccountId();
        return NextResponse.json(users);
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function POST(request: NextRequest) {
      try {
        const body = await request.json();
        const user = await kalendisClient.addUser(body);
        return NextResponse.json(user, { status: 201 });
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function PUT(request: NextRequest) {
      try {
        const body = await request.json();
        const user = await kalendisClient.updateUser(body);
        return NextResponse.json(user);
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function DELETE(request: NextRequest) {
      try {
        const { searchParams } = new URL(request.url);
        const id = searchParams.get('id');
        if (!id) throw new Error('User ID required');
        const result = await kalendisClient.deleteUser({ id });
        return NextResponse.json(result);
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }`;
    
      files['app/api/bookings/route.ts'] = `import { NextRequest, NextResponse } from 'next/server';
    import KalendisClient from '@/lib/kalendisClient';
    
    const kalendisClient = new KalendisClient({ 
      apiKey: process.env.KALENDIS_API_KEY! 
    });
    
    export async function GET(request: NextRequest) {
      try {
        const { searchParams } = new URL(request.url);
        const userId = searchParams.get('userId');
        const start = searchParams.get('start');
        const end = searchParams.get('end') || undefined;
        
        if (!userId || !start) {
          return NextResponse.json({ error: 'userId and start are required' }, { status: 400 });
        }
        
        const bookings = await kalendisClient.getBooking({ userId, start, end });
        return NextResponse.json(bookings);
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function POST(request: NextRequest) {
      try {
        const body = await request.json();
        
        // Check if bulk fetch
        if (body.bookingIds) {
          const bookings = await kalendisClient.getBookingsByIds(body);
          return NextResponse.json(bookings);
        }
        
        // Otherwise create new booking
        const booking = await kalendisClient.addBooking(body);
        return NextResponse.json(booking, { status: 201 });
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function PUT(request: NextRequest) {
      try {
        const body = await request.json();
        const booking = await kalendisClient.updateBooking(body);
        return NextResponse.json(booking);
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function DELETE(request: NextRequest) {
      try {
        const { searchParams } = new URL(request.url);
        const id = searchParams.get('id');
        if (!id) throw new Error('Booking ID required');
        const result = await kalendisClient.deleteBooking({ id });
        return NextResponse.json(result);
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }`;
    
      files['app/api/availability/route.ts'] = `import { NextRequest, NextResponse } from 'next/server';
    import KalendisClient from '@/lib/kalendisClient';
    
    const kalendisClient = new KalendisClient({ 
      apiKey: process.env.KALENDIS_API_KEY! 
    });
    
    export async function GET(request: NextRequest) {
      try {
        const { searchParams } = new URL(request.url);
        const params = Object.fromEntries(searchParams.entries());
        
        // Check which endpoint to call
        if (request.url.includes('/all')) {
          const availability = await kalendisClient.getAllAvailability(params as any);
          return NextResponse.json(availability);
        } else if (request.url.includes('/recurring-availability')) {
          const availability = await kalendisClient.getRecurringAvailability(params as any);
          return NextResponse.json(availability);
        } else if (request.url.includes('/exceptions')) {
          const exceptions = await kalendisClient.getAvailabilityException(params as any);
          return NextResponse.json(exceptions);
        } else {
          const availability = await kalendisClient.getAvailability(params);
          return NextResponse.json(availability);
        }
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function POST(request: NextRequest) {
      try {
        const body = await request.json();
        
        // Route to correct endpoint based on URL
        if (request.url.includes('/calculated')) {
          const result = await kalendisClient.getMultiUserCalculatedAvailability(body);
          return NextResponse.json(result);
        } else if (request.url.includes('/recurring-by-date')) {
          const result = await kalendisClient.getRecurringAvailabilityByDate(body);
          return NextResponse.json(result);
        } else if (request.url.includes('/matching')) {
          const result = await kalendisClient.getMatchingAvailabilityByDate(body);
          return NextResponse.json(result);
        } else if (request.url.includes('/recurring-availability')) {
          const result = await kalendisClient.addRecurringAvailability(body);
          return NextResponse.json(result, { status: 201 });
        } else if (request.url.includes('/exceptions/recurring')) {
          const result = await kalendisClient.addRecurringAvailabilityException(body);
          return NextResponse.json(result, { status: 201 });
        } else if (request.url.includes('/exceptions')) {
          const result = await kalendisClient.addAvailabilityException(body);
          return NextResponse.json(result, { status: 201 });
        } else {
          const availability = await kalendisClient.addAvailability(body);
          return NextResponse.json(availability, { status: 201 });
        }
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function PUT(request: NextRequest) {
      try {
        const body = await request.json();
        
        if (request.url.includes('/recurring-availability')) {
          const result = await kalendisClient.updateRecurringAvailability(body);
          return NextResponse.json(result);
        } else if (request.url.includes('/exceptions')) {
          const result = await kalendisClient.updateAvailabilityException(body);
          return NextResponse.json(result);
        } else {
          const availability = await kalendisClient.updateAvailability(body);
          return NextResponse.json(availability);
        }
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function DELETE(request: NextRequest) {
      try {
        const { searchParams } = new URL(request.url);
        const id = searchParams.get('id');
        if (!id) throw new Error('ID required');
        
        if (request.url.includes('/recurring-availability')) {
          const userId = searchParams.get('userId');
          if (!userId) throw new Error('User ID required');
          const result = await kalendisClient.deleteRecurringAvailability({ id, userId });
          return NextResponse.json(result);
        } else if (request.url.includes('/exceptions')) {
          const userId = searchParams.get('userId');
          if (!userId) throw new Error('User ID required');
          const result = await kalendisClient.deleteAvailabilityException({ id, userId });
          return NextResponse.json(result);
        } else {
          const userId = searchParams.get('userId');
          if (!userId) throw new Error('User ID required');
          const result = await kalendisClient.deleteAvailability({ id, userId });
          return NextResponse.json(result);
        }
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }`;
    
      files['app/api/account/route.ts'] = `import { NextRequest, NextResponse } from 'next/server';
    import KalendisClient from '@/lib/kalendisClient';
    
    const kalendisClient = new KalendisClient({ 
      apiKey: process.env.KALENDIS_API_KEY! 
    });
    
    export async function GET() {
      try {
        const account = await kalendisClient.getAccount();
        return NextResponse.json(account);
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }
    
    export async function PUT(request: NextRequest) {
      try {
        const body = await request.json();
        const account = await kalendisClient.updateAccount(body);
        return NextResponse.json(account);
      } catch (error: any) {
        return NextResponse.json({ error: error.message }, { status: 500 });
      }
    }`;
    
      return files;
    }
  • Helper function generates a complete Express router with handlers for all Kalendis API endpoints using the backend client.
    export function generateExpressRoutes(): string {
      return `import { Request, Response, Router } from 'express';
    import KalendisClient from './kalendisClient';
    
    const router = Router();
    
    const kalendisClient = new KalendisClient({ 
      apiKey: process.env.KALENDIS_API_KEY!
    });
    
    const handleError = (error: any, res: Response) => {
      res.status(500).json({ error: error.message });
    };
    
    router.get('/api/users', async (req, res) => {
      try {
        const users = await kalendisClient.getUsersByAccountId();
        res.json(users);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/users', async (req, res) => {
      try {
        const user = await kalendisClient.addUser(req.body);
        res.status(201).json(user);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.put('/api/users/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const user = await kalendisClient.updateUser({ id, ...req.body });
        res.json(user);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.delete('/api/users/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const result = await kalendisClient.deleteUser({ id });
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.get('/api/availability', async (req, res) => {
      try {
        const availability = await kalendisClient.getAvailability(req.query as any);
        res.json(availability);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.get('/api/availability/all', async (req, res) => {
      try {
        const availability = await kalendisClient.getAllAvailability(req.query as any);
        res.json(availability);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/availability/calculated', async (req, res) => {
      try {
        const result = await kalendisClient.getMultiUserCalculatedAvailability(req.body);
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/availability/recurring', async (req, res) => {
      try {
        const result = await kalendisClient.getRecurringAvailabilityByDate(req.body);
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/availability/matching', async (req, res) => {
      try {
        const result = await kalendisClient.getMatchingAvailabilityByDate(req.body);
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/availability', async (req, res) => {
      try {
        const availability = await kalendisClient.addAvailability(req.body);
        res.status(201).json(availability);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.put('/api/availability/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const availability = await kalendisClient.updateAvailability({ id, ...req.body });
        res.json(availability);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.delete('/api/availability/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const { userId } = req.query as { userId: string };
        const result = await kalendisClient.deleteAvailability({ id, userId });
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.get('/api/recurring-availability', async (req, res) => {
      try {
        const availability = await kalendisClient.getRecurringAvailability(req.query as any);
        res.json(availability);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/recurring-availability', async (req, res) => {
      try {
        const result = await kalendisClient.addRecurringAvailability(req.body);
        res.status(201).json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.put('/api/recurring-availability/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const result = await kalendisClient.updateRecurringAvailability({ id, ...req.body });
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.delete('/api/recurring-availability/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const { userId } = req.query as { userId: string };
        const result = await kalendisClient.deleteRecurringAvailability({ id, userId });
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.get('/api/availability-exceptions', async (req, res) => {
      try {
        const exceptions = await kalendisClient.getAvailabilityException(req.query as any);
        res.json(exceptions);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/availability-exceptions', async (req, res) => {
      try {
        const exception = await kalendisClient.addAvailabilityException(req.body);
        res.status(201).json(exception);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/availability-exceptions/recurring', async (req, res) => {
      try {
        const exceptions = await kalendisClient.addRecurringAvailabilityException(req.body);
        res.status(201).json(exceptions);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.put('/api/availability-exceptions/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const exception = await kalendisClient.updateAvailabilityException({ id, ...req.body });
        res.json(exception);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.delete('/api/availability-exceptions/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const { userId } = req.query as { userId: string };
        const result = await kalendisClient.deleteAvailabilityException({ id, userId });
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.get('/api/bookings', async (req, res) => {
      try {
        const bookings = await kalendisClient.getBooking(req.query as any);
        res.json(bookings);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/bookings/bulk', async (req, res) => {
      try {
        const bookings = await kalendisClient.getBookingsByIds(req.body);
        res.json(bookings);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.post('/api/bookings', async (req, res) => {
      try {
        const booking = await kalendisClient.addBooking(req.body);
        res.status(201).json(booking);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.put('/api/bookings/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const booking = await kalendisClient.updateBooking({ id, ...req.body });
        res.json(booking);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.delete('/api/bookings/:id', async (req, res) => {
      try {
        const { id } = req.params as { id: string };
        const result = await kalendisClient.deleteBooking({ id });
        res.json(result);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.get('/api/account', async (req, res) => {
      try {
        const account = await kalendisClient.getAccount();
        res.json(account);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    router.put('/api/account', async (req, res) => {
      try {
        const account = await kalendisClient.updateAccount(req.body);
        res.json(account);
      } catch (error: any) {
        handleError(error, res);
      }
    });
    
    export default router;
    `;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states what the tool does but lacks details on behavioral traits such as whether it modifies files, requires specific permissions, handles errors, or produces output format. For a generation tool with zero annotation coverage, this is a significant gap.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It is appropriately sized and front-loaded, making it easy to understand quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of generating API route handlers and the lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool outputs (e.g., code files, configuration), how to handle the results, or any dependencies. For a tool with 2 parameters and no structured output information, more context is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents both parameters ('framework' and 'typesImportPath') with descriptions and enums. The description adds no additional meaning beyond what the schema provides, such as explaining how the parameters affect the generation process. Baseline 3 is appropriate when the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Generate API route handlers for Next.js or Express that use the Kalendis backend client.' It specifies the verb ('generate'), resource ('API route handlers'), and technology context. However, it doesn't explicitly differentiate from sibling tools like 'generate-backend-client' or 'generate-frontend-client' beyond mentioning the backend client usage.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It mentions using the Kalendis backend client, but doesn't explain when to choose this over sibling tools like 'generate-backend-client' or 'list-endpoints,' nor does it specify prerequisites or exclusions for usage.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/kalendis-dev/kalendis-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server