🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@cesteral/shared

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cesteral/shared

Shared infrastructure utilities and authentication for Cesteral MCP servers

latest
Source
npmnpm
Version
1.2.0
Version published
Maintainers
1
Created
Source

@cesteral/shared

Shared infrastructure utilities, authentication, and types for Cesteral MCP servers.

Installation

All MCP server packages depend on this package via pnpm workspace protocol (workspace:*). No separate installation is needed.

Modules

Authentication (/auth)

ModuleKey ExportsPurpose
auth-strategy.tsAuthStrategy, AuthInfo, AuthResult, createAuthStrategy()Pluggable auth strategy factory (google-headers, jwt, none)
bearer-auth-strategy-base.tsBearerAuthStrategyBaseAbstract base for platform-specific bearer auth (Meta, LinkedIn, TikTok, Pinterest, Snapchat, Amazon DSP, Microsoft Ads)
google-auth.tsGoogleAuthAdapter, ServiceAccountAuthAdapter, OAuth2RefreshTokenAuthAdapter, parseCredentialsFromHeaders()Google OAuth2/SA token management with caching
jwt.tsverifyJwt(), createJwt(), extractBearerToken(), decodeJwtPayload()JWT verification and creation via jose library

Example: Creating an auth strategy

import { createAuthStrategy } from "@cesteral/shared";

const strategy = createAuthStrategy("jwt", { secretKey: process.env.MCP_AUTH_SECRET_KEY });
const result = await strategy.verify(request.headers);
// result: { authInfo, googleAuthAdapter?, platformAuthAdapter?, credentialFingerprint? }

Utilities (/utils)

Core Infrastructure

ModuleKey ExportsPurpose
server-bootstrap.tsbootstrapMcpServer(), detectTransportMode()Main orchestrator: OTEL init, stdio/HTTP branching, graceful shutdown
mcp-http-transport-factory.tscreateMcpHttpTransport(), startMcpHttpServer()Hono-based MCP HTTP transport with CORS, session management, RFC 9728
mcp-transport-helpers.tsSessionManager, validateSessionReuse(), buildAllowedOrigins()Session lifecycle, credential fingerprinting, protocol version validation
config-base.tsBaseConfigSchema, getBaseEnvConfig(), parseConfigWithSchema()Zod-based environment configuration with defaults

Tool Registration

ModuleKey ExportsPurpose
tool-handler-factory.tsregisterToolsFromDefinitions(), ToolDefinitionForFactoryCore factory that eliminates ~90 lines of boilerplate per server. Handles Zod validation, OTEL spans, JWT scope enforcement, interaction logging, response formatting, error handling
prompt-handler-factory.tsregisterPromptsFromDefinitions()Prompt registration with standardized handling
resource-handler-factory.tsregisterStaticResourcesFromDefinitions()Static resource registration
zod-helpers.tsextractZodShape()Unwraps ZodEffects for MCP SDK registration

Example: Registering tools

import { registerToolsFromDefinitions } from "@cesteral/shared";

registerToolsFromDefinitions({
  server: mcpServer,
  tools: allTools,
  resolveServices: (ctx) => resolveSessionServices(ctx),
  logger,
  rateLimiter,
});

Session Management

ModuleKey ExportsPurpose
session-store.tsSessionServiceStore<T>Typed Map from sessionId to services with credential fingerprinting
session-resolver.tsresolveSessionServicesFromStore()Session lookup with descriptive error on missing sessions

Example: Session store

import { SessionServiceStore } from "@cesteral/shared";

const store = new SessionServiceStore<MyServices>();
store.set(sessionId, services);
const services = resolveSessionServicesFromStore(store, sdkContext);

Networking & HTTP

ModuleKey ExportsPurpose
fetch-with-timeout.tsfetchWithTimeout()Fetch with AbortController timeout and request ID tracing
retryable-fetch.tsexecuteWithRetry()Exponential backoff on 429/5xx with Retry-After support
download-file.tsdownloadFileToBuffer()URL-to-buffer download for platform upload tools
multipart-form.tsbuildMultipartFormData()Multipart/form-data construction for binary file uploads

Rate Limiting

ModuleKey ExportsPurpose
rate-limiter.tsRateLimiter, createPlatformRateLimiter()In-memory sliding window rate limiter with wildcard pattern support

Example: Rate limiter

import { createPlatformRateLimiter } from "@cesteral/shared";

const limiter = createPlatformRateLimiter("dv360", 100); // 100 req/min
await limiter.consume(sessionId); // throws McpError if rate exceeded

Logging & Errors

ModuleKey ExportsPurpose
logger.tscreateLogger()Pino logger factory with pino-pretty in development
mcp-errors.tsMcpError, JsonRpcErrorCode, ErrorHandlerStructured MCP error handling with JSON-RPC code mapping
request-context.tsrunWithRequestContext(), getRequestContext(), createRequestContext()AsyncLocalStorage-based request correlation with UUIDs
interaction-logger.tsInteractionLoggerAppend-only JSONL logger with file rotation and optional GCS persistence

Example: Error handling

import { McpError, JsonRpcErrorCode } from "@cesteral/shared";

throw new McpError(JsonRpcErrorCode.NotFound, "Campaign not found", { campaignId });
// Automatically serialized to JSON-RPC error response by the tool factory

Telemetry

ModuleKey ExportsPurpose
telemetry.tsinitializeOpenTelemetry(), withToolSpan(), otelLogMixin(), shutdownOpenTelemetry()OpenTelemetry SDK init with GCP Cloud Run detection, span helpers
metrics.tsrecordToolExecution(), registerActiveSessionsGauge(), recordAuthValidation(), recordRateLimitHit()Business metrics: tool execution counters/histograms, session gauges, auth/rate-limit counters

Validation & Helpers

ModuleKey ExportsPurpose
client-validation-helpers.tsvalidateRequiredFields(), checkReadOnlyFields()Client-side entity validation without API calls
elicitation-helpers.tselicitArchiveConfirmation()User confirmation for irreversible operations
bulk-operation-schemas.tsBulkOperationResultSchemaZod schema for bulk operation results

Conformance Testing

ModuleKey ExportsPurpose
conformance-echo-tool.tsconformanceTools6 test tools (echo, text, logging, elicitation variants) for MCP protocol conformance
conformance-fixtures.tsconformanceResources, conformancePromptsTest resources and prompts
tool-examples-resource.tscreateToolExamplesResource(), createServerCapabilitiesResource()Auto-generated MCP Resources from tool metadata

Types (/types)

ModuleKey ExportsPurpose
tool-types.tsToolDefinition, SdkContext, ResourceDefinition, ElicitResultLikeCore type definitions for tool/resource registration

Usage

// Import utilities
import { createLogger, McpError, JsonRpcErrorCode } from "@cesteral/shared/utils";

// Import auth
import { createAuthStrategy, verifyJwt } from "@cesteral/shared/auth";

// Or import everything from barrel
import { createLogger, createAuthStrategy, registerToolsFromDefinitions } from "@cesteral/shared";

Context Efficiency Standards

  • If a tool defines outputSchema, keep text responses concise and return full payload via structuredContent.
  • Avoid embedding large JSON blobs in human-readable text fields.
  • Keep tool descriptions short; place detailed workflows in MCP prompts/resources.
  • Prefer compact default text formatting in shared tool handlers unless pretty output is explicitly required.

Development

pnpm run build       # Build
pnpm run typecheck   # Type check
pnpm run test        # Test
pnpm run lint        # Lint

Contributing

See root CLAUDE.md for development guidelines, build system details, and monorepo conventions. See the root README for full architecture context.

License

Apache License 2.0 -- see LICENSE for details. This package is part of Cesteral's open-source connector layer; Cesteral Intelligence and higher-level governance features live outside this repository.

Keywords

mcp

FAQs

Package last updated on 10 Jun 2026

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