Skip to main content

@leanmcp/env-injection

Request-scoped environment variable injection for LeanMCP tools. Enables user-specific secrets (API keys, tokens) to be securely fetched and accessed within MCP tool methods.
This package only works with the LeanMCP auth provider and requires a projectId to be configured. Users manage their own secrets through the LeanMCP dashboard.

Features

  • Request-scoped isolation - Each user’s secrets are isolated using AsyncLocalStorage
  • @RequireEnv decorator - Validate required secrets exist before method execution
  • getEnv() / getAllEnv() - Access user-specific secrets in your tool code
  • Concurrency safe - Each request has its own isolated context

Installation

Quick Start

1. Configure Auth Provider with projectId

2. Use @RequireEnv and getEnv()

How It Works

  1. User makes request with auth token
  2. @Authenticated verifies token and fetches user’s secrets from LeanMCP API
  3. Secrets are stored in AsyncLocalStorage for this request only
  4. @RequireEnv validates required secrets exist
  5. getEnv() accesses secrets during method execution
  6. Context is automatically cleaned up after request completes

API Reference

@RequireEnv(keys)

Decorator to validate required environment variables exist before method execution.
Requirements:
  • Must be used with @Authenticated(authProvider, { projectId })
  • Throws clear error if projectId is not configured
  • Throws if required keys are missing

getEnv(key)

Get a single environment variable from the current request context.

getAllEnv()

Get all environment variables from the current request context.

hasEnvContext()

Check if currently inside an env context.

runWithEnv(env, fn)

Run a function with environment variables in scope. Used internally by @Authenticated.

Error Messages

Missing projectId Configuration

Missing Required Variables

Called Outside Context

Environment Variables

Best Practices

Environment injection requires the projectId option to know which project’s secrets to fetch.
Fails fast with clear error messages if secrets are missing.
After @RequireEnv validates, secrets are guaranteed to exist.
They’re request-scoped for security. Always call getEnv() when needed.