npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

loopback4-mcp

v1.0.3

Published

A loopback extension that exposes API to MCP Tools.

Readme

loopback4-mcp

Overview

This extension provides a plug-and-play integration between LoopBack4 applications and Model Context Protocol (MCP) specification. Its purpose is to enable LoopBack APIs, services, and business logic to be exposed as MCP Tools, allowing external MCP clients (such as LLMs, agents, or MCP-compatible apps) to discover and execute server-defined operations.

Key Features

  • Automatic MCP Tool Discovery: The extension scans your application at boot time and automatically registers all methods decorated with the custom @mcpTool() decorator. This allows you to define MCP tools anywhere in your LoopBack project without manually wiring metadata.

  • Lifecycle-managed Tool Registry: A dedicated McpToolRegistry service maintains all discovered tool metadata, their handlers, and execution context. A McpToolRegistryBootObserver ensures that registration happens only after the application has fully booted.

  • Hook System Support: Built-in support for pre and post hooks that enable validation, logging, audit trails, and custom business logic around tool execution.

  • Authorization Integration: Seamless integration with LoopBack's authorization system, ensuring MCP tools respect your existing permission structure.

  • Simplified Endpoint Format: Easy-to-use POST endpoint that accepts tool arguments directly without complex MCP protocol wrapping.

Installation

npm install loopback4-mcp

Integration Steps

Step 1: Create Binding Keys

Create a src/keys.ts file to define binding keys for MCP hooks:

import {BindingKey} from '@loopback/core';

export namespace McpHookBindings {
  export const PRE_HOOK = BindingKey.create<Function>('hooks.mcp.preHook');
  export const POST_HOOK = BindingKey.create<Function>('hooks.mcp.postHook');
}

Step 2: Create Hook Providers

Create hook providers to implement pre and post-hook functionality:

// src/providers/mcp-pre-hook.provider.ts
import {inject, Provider} from '@loopback/core';
import {McpHookContext} from 'loopback4-mcp';

export class McpPreHookProvider implements Provider<Function> {
  value(): Function {
    return async (context: McpHookContext) => {
      console.log(`Pre-hook executing for tool: ${context.toolName}`);
      // Add validation, sanitization, or pre-processing logic here
    };
  }
}

// src/providers/mcp-post-hook.provider.ts
export class McpPostHookProvider implements Provider<Function> {
  value(): Function {
    return async (context: McpHookContext) => {
      console.log(`Post-hook executing for tool: ${context.toolName}`);
      // Add logging, audit trails, or post-processing logic here
    };
  }
}

Step 3: Configure Application

Update your src/application.ts to bind the component and hooks:

export class MyApplication extends BootMixin(
  ServiceMixin(RepositoryMixin(RestApplication)),
) {
  constructor(options: ApplicationConfig = {}) {
    // Bind MCP component
    this.component(McpComponent);

    // Bind hook providers
    this.bind(McpHookBindings.PRE_HOOK).toProvider(McpPreHookProvider);
    this.bind(McpHookBindings.POST_HOOK).toProvider(McpPostHookProvider);
  }
}

Step 4: Create MCP Tool Controllers

Add the @mcpTool() decorator to controller methods you want to expose as MCP tools. Here's a complete example showing the decorator stack with authorization and authentication:

export class UserController {
  constructor(
    @repository(UserRepository)
    public userRepository: UserRepository,
  ) {}

  @authorize({
    permissions: [PermissionKey.CreateUser],
  })
  @authenticate(STRATEGY.BEARER, {
    passReqToCallback: true,
  })
  @mcpTool({
    name: 'createUser',
    description: 'Create a new user in the system',
    preHook: {binding: HookBindings.PRE_HOOK},
    postHook: {binding: HookBindings.POST_HOOK},
  })
  @post('/users', {
    security: OPERATION_SECURITY_SPEC,
    responses: {
      [STATUS_CODE.OK]: {
        description: 'User model instance',
        content: {
          'application/json': {schema: getModelSchemaRefSF(User)},
        },
      },
    },
  })
  async create(
    @param.query.object('user') user: Omit<User, 'id'>,
  ): Promise<object> {
    const created = await this.userRepository.create(user as User);

    return {
      content: [{
        type: 'text',
        text: `Successfully created user with id: ${created.id}`
      }]
    };
  }
}

Parameter Decorator Guidelines

Critical: Use correct LoopBack @param decorators based on your route structure.

Path Parameters

@get('/users/{id}')
async findById(
  @param.path.string('id') id: string,  // ✅ Correct for /users/{id}
): Promise<User> {
  return this.userRepository.findById(id);
}

Query Parameters

@get('/users')
async findAll(
  @param.query.string('name') name?: string,  // ✅ Correct for /users?name=value
): Promise<User[]> {
  return this.userRepository.find({where: {name}});
}

Request Body Parameters

@post('/users')
async create(
  @param.request.body('user') user: User,  // ✅ Correct for POST body
): Promise<User> {
  return this.userRepository.create(user);
}

Common Mistakes:

  • ❌ Using @param.query.string('id') for /users/{id} routes
  • ✅ Use @param.path.string('id') for path parameters

Decorator Configuration

The @mcpTool() decorator accepts the following configuration:

@mcpTool({
  // Required fields
  name: 'tool-name',              // Unique identifier for the tool
  description: 'Tool description',  // Human-readable description

  // Optional fields
  schema: {                         // Zod validation schema
    email: z.string().email(),
    age: z.number().min(18),
  },
  preHookBinding: BindingKey.create('hooks.pre'),  // Pre-hook binding key
  postHookBinding: BindingKey.create('hooks.post'), // Post-hook binding key
})

Testing

Using MCP Inspector

The easiest way to test and visualize your MCP tools is using the MCP Inspector. This provides a web interface where all your endpoints are available and you can see hook responses in real-time.

Start MCP Inspector:

npx @modelcontextprotocol/inspector http://localhost:3000/mcp

What MCP Inspector shows:

  • All Available Tools: Complete list of MCP tools exposed by your application
  • Tool Details: Names, descriptions, and parameter schemas
  • Live Testing: Test each tool directly from the web interface
  • Request/Response: Real-time request and response data
  • Hook Execution: Visualize pre and post-hook execution and their responses
  • Error Handling: See error messages and debugging information

Workflow with MCP Inspector:

  1. Start your LoopBack application
  2. Run MCP Inspector with your MCP endpoint URL
  3. Browse available tools in the web interface
  4. Test tools with different parameters
  5. Monitor hook execution and responses
  6. Debug issues using the detailed logs

License

MIT

Support