You're Invited:Meet the Socket Team at RSAC and BSidesSF 2026, March 23–26.RSVP
Socket
Book a DemoSign in
Socket

@mcp-apps-kit/core

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mcp-apps-kit/core

Server-side framework for building MCP applications

Source
npmnpm
Version
0.2.3
Version published
Weekly downloads
16
-36%
Maintainers
1
Weekly downloads
 
Created
Source

@mcp-apps-kit/core

npm node license

Server-side TypeScript framework for building interactive MCP apps that can run on both:

  • Claude Desktop (MCP Apps)
  • ChatGPT (OpenAI Apps SDK)

It provides a single createApp() API to define tools, validate inputs/outputs with Zod v4, and attach UI resources to tool responses.

Install

npm install @mcp-apps-kit/core zod
  • Node.js: >=18
  • Zod: ^4.0.0

Quick start

Create an app with one tool using the defineTool helper for full type safety:

import { createApp, defineTool } from "@mcp-apps-kit/core";
import { z } from "zod";

const app = createApp({
  name: "my-app",
  version: "1.0.0",

  tools: {
    greet: defineTool({
      description: "Greet a user",
      input: z.object({
        name: z.string().describe("Name to greet"),
      }),
      output: z.object({ message: z.string() }),
      handler: async (input) => {
        // input.name is fully typed - no assertion needed!
        return { message: `Hello, ${input.name}!` };
      },
    }),
  },
});

await app.start({ port: 3000 });

Type-Safe Tool Definitions

The defineTool Helper

Use defineTool to get automatic type inference in your handlers:

import { defineTool } from "@mcp-apps-kit/core";

tools: {
  search: defineTool({
    input: z.object({
      query: z.string(),
      maxResults: z.number().optional(),
    }),
    handler: async (input) => {
      // ✅ input.query and input.maxResults are fully typed!
      return { results: await search(input.query, input.maxResults) };
    },
  }),
}

Why defineTool?

With Zod v4, TypeScript cannot infer concrete schema types across module boundaries when using generic z.ZodType. The defineTool helper captures specific schema types at the call site, enabling proper type inference without manual type assertions.

Alternative: Object Syntax with Type Assertions

If you prefer not to use defineTool, you can use the object syntax directly, but you'll need type assertions:

// Define schema separately
const searchInput = z.object({
  query: z.string(),
  maxResults: z.number().optional(),
});

const app = createApp({
  tools: {
    search: {
      input: searchInput,
      handler: async (input) => {
        // Manual type assertion required
        const typed = input as z.infer<typeof searchInput>;
        return { results: await search(typed.query, typed.maxResults) };
      },
    },
  },
});

Zod v4 Schema Descriptions

Use .describe() to add descriptions that appear in tool parameter documentation:

const myTool = defineTool({
  description: "Search for items",
  input: z.object({
    query: z.string().describe("Search query text"),
    maxResults: z.number().optional().describe("Maximum number of results to return"),
  }),
  handler: async (input) => {
    // input is fully typed
    return { results: [] };
  },
});

Attach UI to tool outputs

Tools can optionally reference a UI resource by ID (e.g. "restaurant-list"). The host can then render the returned HTML as a widget.

A common pattern is to return both:

  • the model-visible output (typed by your Zod output schema), and
  • UI-only payload in _meta.
import { createApp } from "@mcp-apps-kit/core";
import { z } from "zod";

const app = createApp({
  name: "restaurant-finder",
  version: "1.0.0",
  tools: {
    search_restaurants: {
      description: "Search for restaurants by location",
      input: z.object({ location: z.string() }),
      output: z.object({ count: z.number() }),
      handler: async ({ location }) => {
        const restaurants = await fetchRestaurants(location);
        return {
          count: restaurants.length,
          _meta: { restaurants },
        };
      },
      ui: "restaurant-list",
    },
  },
  ui: {
    "restaurant-list": {
      html: "./dist/widget.html",
    },
  },
});

Plugins, Middleware & Events

Extend your app with cross-cutting concerns (logging, authentication, analytics) using plugins, middleware, and events.

Plugins

Plugins provide hooks into the application lifecycle and tool execution:

import { createPlugin } from "@mcp-apps-kit/core";

const loggingPlugin = createPlugin({
  name: "logger",
  version: "1.0.0",

  // Lifecycle hooks
  onInit: async () => console.log("App initializing..."),
  onStart: async () => console.log("App started"),

  // Tool execution hooks
  beforeToolCall: async (context) => {
    console.log(`Tool called: ${context.toolName}`);
  },
  afterToolCall: async (context, result) => {
    console.log(`Tool completed: ${context.toolName}`);
  },
  onToolError: async (context, error) => {
    console.error(`Tool failed: ${context.toolName}`, error);
  },
});

const app = createApp({
  name: "my-app",
  version: "1.0.0",
  plugins: [loggingPlugin],
  tools: {
    /* ... */
  },
});

Middleware

Middleware processes requests in a pipeline, similar to Express or Koa:

import type { Middleware } from "@mcp-apps-kit/core";

// Request logging middleware
const logger: Middleware = async (context, next) => {
  const start = Date.now();
  console.log(`Processing ${context.toolName}...`);

  // Store data in context.state (shared with other middleware & handler)
  context.state.set("startTime", start);

  await next(); // Call next middleware or tool handler

  const duration = Date.now() - start;
  console.log(`${context.toolName} completed in ${duration}ms`);
};

// Register middleware (executed in order)
app.use(logger);
app.use(rateLimiter);
app.use(authenticator);

Events

Listen to application events for analytics and monitoring:

// Track application lifecycle
app.on("app:init", ({ config }) => {
  console.log(`App initialized: ${config.name}`);
});

app.on("app:start", ({ transport }) => {
  console.log(`Started with transport: ${transport}`);
});

// Monitor tool execution
app.on("tool:called", ({ toolName, input }) => {
  analytics.track("tool_called", { tool: toolName });
});

app.on("tool:success", ({ toolName, duration }) => {
  metrics.timing("tool_duration", duration, { tool: toolName });
});

app.on("tool:error", ({ toolName, error }) => {
  errorTracker.report(error, { tool: toolName });
});

See the kanban-mcp-example for a complete demonstration.

Debug Logging

Enable debug logging to receive structured logs from client UIs through the MCP protocol. This is especially useful in sandboxed environments (like mobile ChatGPT) where console access is restricted.

Server Configuration

const app = createApp({
  name: "my-app",
  version: "1.0.0",
  tools: {
    /* ... */
  },
  config: {
    debug: {
      logTool: true, // Enable debug logging
      level: "debug", // "debug" | "info" | "warn" | "error"
    },
  },
});

When enabled, the server:

  • Registers an internal log_debug tool (hidden from the model)
  • Receives batched log entries from connected client UIs
  • Outputs logs to the server console with timestamps and source info

Log Levels

LevelDescription
debugAll logs including debug info
infoInfo, warning, and error logs
warnWarning and error logs only
errorError logs only

Using the Debug Logger (Server-side)

You can also use the debug logger directly in your server code:

import { debugLogger } from "@mcp-apps-kit/core";

// Log messages at different levels
debugLogger.debug("Processing request", { requestId: "123" });
debugLogger.info("User logged in", { userId: "456" });
debugLogger.warn("Rate limit approaching", { remaining: 10 });
debugLogger.error("Database connection failed", { error: err.message });

See also: @mcp-apps-kit/ui README for client-side logging.

OAuth 2.1 Authentication

Secure your MCP server with OAuth 2.1 bearer token validation. The framework includes built-in JWT verification with automatic JWKS discovery, complying with RFC 6750 (Bearer Token Usage) and RFC 8414 (Authorization Server Metadata).

Quick Start

import { createApp } from "@mcp-apps-kit/core";

const app = createApp({
  name: "my-app",
  version: "1.0.0",
  tools: {
    /* ... */
  },
  oauth: {
    protectedResource: "http://localhost:3000",
    authorizationServer: "https://auth.example.com",
    scopes: ["mcp:read", "mcp:write"], // Optional: required scopes
  },
});

Configuration

OptionTypeRequiredDescription
protectedResourcestringPublic URL of this MCP server (used as default audience)
authorizationServerstringIssuer URL of OAuth 2.1 authorization server
jwksUristringExplicit JWKS URI (auto-discovered if not provided)
algorithmsstring[]Allowed JWT algorithms (default: ["RS256"])
audiencestring | string[]Expected audience claim (default: protectedResource)
scopesstring[]Required OAuth scopes for all requests
tokenVerifierTokenVerifierCustom token verification (for non-JWT tokens or introspection)

How It Works

  • Automatic Discovery: Framework discovers JWKS endpoint via /.well-known/oauth-authorization-server
  • Request Validation: Bearer tokens are validated before tool execution
  • Auth Context Injection: Authenticated user info is injected into tool handlers

Important: This server is a protected resource (API/service that requires OAuth tokens), NOT an authorization server. The OAuth endpoints exposed by this framework provide metadata about the external authorization server that issues tokens, not authentication functionality itself.

OAuth Metadata Endpoints

When OAuth is enabled, the framework exposes two metadata endpoints:

  • /.well-known/oauth-authorization-server: Returns metadata about your external authorization server (e.g., Auth0, Keycloak)
  • /.well-known/oauth-protected-resource: Returns metadata about this protected resource (scopes, authorization servers)

These endpoints help clients discover OAuth configuration, but do not provide token issuance or user authentication.

tools: {
  get_user_data: defineTool({
    description: "Get authenticated user data",
    input: z.object({}),
    handler: async (input, context) => {
      // Access authenticated user information
      const auth = context.auth;

      console.log("User ID:", auth.subject);
      console.log("Scopes:", auth.scopes);
      console.log("Expires at:", new Date(auth.expiresAt * 1000));

      return { userId: auth.subject };
    },
  }),
}

Auth Context Properties

When OAuth is enabled, tool handlers receive authenticated context via context.auth:

interface AuthContext {
  subject: string; // User identifier (JWT 'sub' claim)
  scopes: string[]; // OAuth scopes granted to token
  expiresAt: number; // Token expiration (Unix timestamp)
  clientId: string; // OAuth client ID
  issuer: string; // Token issuer (authorization server)
  audience: string | string[]; // Token audience
  token?: string; // Original bearer token
  extra?: Record<string, unknown>; // Additional JWT claims
}

Error Responses

The framework returns RFC 6750-compliant error responses:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="http://localhost:3000",
                  error="invalid_token",
                  error_description="Token expired"
Error CodeStatusDescription
invalid_request400Malformed request
invalid_token401Token expired, revoked, or malformed
insufficient_scope403Token missing required scopes

Custom Token Verification

For non-JWT tokens or token introspection:

import type { TokenVerifier } from "@mcp-apps-kit/core";

const customVerifier: TokenVerifier = {
  async verifyAccessToken(token: string) {
    // Call your token introspection endpoint
    const response = await fetch("https://auth.example.com/introspect", {
      method: "POST",
      body: new URLSearchParams({ token }),
    });

    const data = await response.json();

    if (!data.active) {
      throw new Error("Token inactive");
    }

    return {
      token,
      clientId: data.client_id,
      scopes: data.scope.split(" "),
      expiresAt: data.exp,
      extra: { subject: data.sub },
    };
  },
};

const app = createApp({
  oauth: {
    protectedResource: "http://localhost:3000",
    authorizationServer: "https://auth.example.com",
    tokenVerifier: customVerifier, // Use custom verifier
  },
});

Security Features

  • JWT Signature Verification: RSA/ECDSA signature validation via JWKS
  • Claim Validation: Automatic validation of iss, aud, exp, sub, client_id
  • Scope Enforcement: Optional scope validation for all requests
  • Issuer Normalization: Handles trailing slash differences
  • Clock Skew Tolerance: 5-second tolerance for timestamp validation
  • HTTPS Enforcement: JWKS URIs must use HTTPS in production
  • Subject Override: Framework overrides client-provided subject for security

Production Considerations

  • HTTPS Required: JWKS URIs must use HTTPS in production environments
  • Key Caching: JWKS keys are cached with automatic refresh (10-minute TTL)
  • Rate Limiting: Built-in rate limiting for JWKS requests (10 requests/minute)
  • Error Handling: All validation errors return proper WWW-Authenticate headers

Testing Without OAuth

Disable OAuth for development/testing:

const app = createApp({
  name: "my-app",
  version: "1.0.0",
  tools: {
    /* ... */
  },
  // No oauth config = OAuth disabled
});

What you get

  • A single place to define tools + UI resources
  • Runtime validation via Zod + strong TypeScript inference
  • Protocol-aware metadata generation for both Claude and ChatGPT hosts

Documentation & examples

  • Project overview: ../../README.md
  • Examples:
    • kanban-mcp-example (comprehensive demo)
    • ../../examples/minimal
    • ../../examples/restaurant-finder

License

MIT

Keywords

mcp

FAQs

Package last updated on 28 Dec 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts