@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
- User makes request with auth token
@Authenticatedverifies token and fetches user’s secrets from LeanMCP API- Secrets are stored in
AsyncLocalStoragefor this request only @RequireEnvvalidates required secrets existgetEnv()accesses secrets during method execution- Context is automatically cleaned up after request completes
API Reference
@RequireEnv(keys)
Decorator to validate required environment variables exist before method execution.- Must be used with
@Authenticated(authProvider, { projectId }) - Throws clear error if
projectIdis 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
| Variable | Description |
|---|---|
LEANMCP_API_KEY | Your LeanMCP API key (with SDK scope) |
LEANMCP_PROJECT_ID | Project ID to scope secrets to |
Best Practices
Always use @Authenticated with projectId
Always use @Authenticated with projectId
Environment injection requires the
projectId option to know which project’s secrets to fetch.Use @RequireEnv for validation
Use @RequireEnv for validation
Fails fast with clear error messages if secrets are missing.
Use non-null assertion after @RequireEnv
Use non-null assertion after @RequireEnv
After
@RequireEnv validates, secrets are guaranteed to exist.Don't cache secrets
Don't cache secrets
They’re request-scoped for security. Always call
getEnv() when needed.Related Packages
- @leanmcp/auth - Authentication decorators (required)
- @leanmcp/core - Core MCP server functionality