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.
-
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
McpToolRegistryservice maintains all discovered tool metadata, their handlers, and execution context. AMcpToolRegistryBootObserverensures 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.
npm install loopback4-mcpCreate 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');
}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
};
}
}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);
}
}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}`
}]
};
}
}Critical: Use correct LoopBack @param decorators based on your route structure.
@get('/users/{id}')
async findById(
@param.path.string('id') id: string, // ✅ Correct for /users/{id}
): Promise<User> {
return this.userRepository.findById(id);
}@get('/users')
async findAll(
@param.query.string('name') name?: string, // ✅ Correct for /users?name=value
): Promise<User[]> {
return this.userRepository.find({where: {name}});
}@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
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
})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/mcpWhat 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:
- Start your LoopBack application
- Run MCP Inspector with your MCP endpoint URL
- Browse available tools in the web interface
- Test tools with different parameters
- Monitor hook execution and responses
- Debug issues using the detailed logs
- GitHub Issues: sourcefuse/loopback4-mcp/issues
- Documentation: loopback.io
