{"_id":"@agentshieldhq/langchain","name":"@agentshieldhq/langchain","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@agentshieldhq/langchain","version":"1.0.0","description":"AgentShield LangChain integration — callback handler for AI agent policy governance","main":"dist/index.js","types":"dist/index.d.ts","type":"module","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","default":"./dist/index.js"}},"scripts":{"build":"tsc","prepublishOnly":"npm run build","test":"vitest run","test:watch":"vitest","lint":"tsc --noEmit"},"keywords":["agentshield","langchain","ai","agent","policy","governance","guardrails","callback","tool-call","safety","shield","langgraph","openai"],"license":"Apache-2.0","repository":{"type":"git","url":"git+https://github.com/sharif418/agentshield.git","directory":"packages/langchain"},"homepage":"https://github.com/sharif418/agentshield#readme","sideEffects":false,"peerDependencies":{"langchain":">=0.1.0"},"peerDependenciesMeta":{"langchain":{"optional":true}},"dependencies":{"@agentshieldhq/sdk":"^1.0.0","@agentshieldhq/core":"^1.0.0"},"devDependencies":{"typescript":"^5","vitest":"^4.1.4"},"publishConfig":{"access":"public"},"gitHead":"f66e9ad4d9171818d6474a892fe586533f180fdf","_id":"@agentshieldhq/langchain@1.0.0","bugs":{"url":"https://github.com/sharif418/agentshield/issues"},"_nodeVersion":"25.6.1","_npmVersion":"11.9.0","dist":{"integrity":"sha512-71fkZMUcLKcLUMTioiykQfS1WQrMwhxDCRrCv43bPGCFli13pG7n2vEuAVdKAb/bs2e+Aq5sLEHCpAWzdMwemw==","shasum":"efbbfb3a4930003e285becd24b416763ec672c11","tarball":"https://registry.npmjs.org/@agentshieldhq/langchain/-/langchain-1.0.0.tgz","fileCount":17,"unpackedSize":75913,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIHqqGVDR1T1JAtPq1resEkR6SYb9ALgMzQOfqDamOkNrAiB7RyOSTJNReBsXa2lIznJG4maWrMKAs2yAfHfYVNDe/w=="}]},"_npmUser":{"name":"sharif418","email":"m0hammadnasrullah326@gmail.com"},"directories":{},"maintainers":[{"name":"sharif418","email":"m0hammadnasrullah326@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/langchain_1.0.0_1777468343044_0.5578118768612412"},"_hasShrinkwrap":false}},"time":{"created":"2026-04-29T13:12:22.938Z","1.0.0":"2026-04-29T13:12:23.198Z","modified":"2026-04-29T13:12:23.420Z"},"maintainers":[{"name":"sharif418","email":"m0hammadnasrullah326@gmail.com"}],"description":"AgentShield LangChain integration — callback handler for AI agent policy governance","homepage":"https://github.com/sharif418/agentshield#readme","keywords":["agentshield","langchain","ai","agent","policy","governance","guardrails","callback","tool-call","safety","shield","langgraph","openai"],"repository":{"type":"git","url":"git+https://github.com/sharif418/agentshield.git","directory":"packages/langchain"},"bugs":{"url":"https://github.com/sharif418/agentshield/issues"},"license":"Apache-2.0","readme":"# @agentshieldhq/langchain\n\n[![npm version](https://img.shields.io/npm/v/@agentshieldhq/langchain.svg)](https://www.npmjs.com/package/@agentshieldhq/langchain) [![license](https://img.shields.io/npm/l/@agentshieldhq/langchain.svg)](https://github.com/agentshield/agentshield/blob/main/LICENSE) [![TypeScript](https://img.shields.io/badge/TypeScript-5-blue.svg)](https://www.typescriptlang.org/)\n\nLangChain callback handler for AI agent policy governance. Automatically intercepts tool calls and evaluates them through AgentShield's policy engine.\n\n## Installation\n\n```bash\nnpm install @agentshieldhq/langchain\n```\n\n**Peer dependency:** `langchain >= 0.1.0` (optional — the handler works with any callback system that calls `handleToolStart` / `handleToolEnd`).\n\n## Quick Start\n\n### Embedded Mode (No Server Needed)\n\n```typescript\nimport { AgentShieldCallbackHandler } from '@agentshieldhq/langchain';\nimport { AgentExecutor } from 'langchain/agents';\n\nconst handler = new AgentShieldCallbackHandler({\n  mode: 'embedded',\n  policies: [\n    {\n      policyId: 'POL-001',\n      name: 'Block SQL DROP',\n      agentRole: 'DataAgent',\n      resource: 'PostgreSQL',\n      action: 'DROP',\n      permissionLevel: 'BLOCK',\n      priority: 20,\n      enabled: true,\n    },\n    {\n      policyId: 'POL-002',\n      name: 'Require approval for writes',\n      agentRole: 'DataAgent',\n      resource: 'PostgreSQL',\n      action: 'WRITE',\n      permissionLevel: 'REQUIRE_APPROVAL',\n      priority: 10,\n      enabled: true,\n    },\n  ],\n  defaultAgentRole: 'DataAgent',\n  toolNameMap: { 'sql_db_query': 'PostgreSQL' },\n});\n\n// Attach to an AgentExecutor\nconst executor = AgentExecutor.fromAgentAndTools({\n  agent,\n  tools,\n  callbacks: [handler],\n});\n```\n\n### Hosted Mode (Connects to Server)\n\n```typescript\nimport { AgentShieldCallbackHandler } from '@agentshieldhq/langchain';\n\nconst handler = new AgentShieldCallbackHandler({\n  serverUrl: 'https://agentshield.example.com',\n  mode: 'hosted',\n  apiKey: 'sk-...',\n  defaultAgentRole: 'CodeAgent',\n  onBlock: 'return',\n  onRequireApproval: 'allow',\n});\n\nconst executor = AgentExecutor.fromAgentAndTools({\n  agent,\n  tools,\n  callbacks: [handler],\n});\n```\n\n### With LangGraph\n\n```typescript\nconst handler = new AgentShieldCallbackHandler({\n  mode: 'embedded',\n  policies: [/* ... */],\n  defaultAgentRole: 'ResearchAgent',\n});\n\nconst result = await graph.invoke(\n  { messages: [/* ... */] },\n  { callbacks: [handler] }\n);\n```\n\n## Configuration\n\n### `AgentShieldLangChainConfig`\n\nExtends the base `AgentShieldConfig` with LangChain-specific options:\n\n```typescript\ninterface AgentShieldLangChainConfig extends AgentShieldConfig {\n  /** What to do when a tool call is blocked.\n   *  - 'throw' — throw AgentShieldBlockError (default)\n   *  - 'return' — replace tool output with block message\n   */\n  onBlock?: 'throw' | 'return';\n\n  /** What to do when a tool call requires approval.\n   *  - 'throw' — throw AgentShieldApprovalError (default)\n   *  - 'return' — replace tool output with approval message\n   *  - 'allow' — let the tool call through (async approval workflow)\n   */\n  onRequireApproval?: 'throw' | 'return' | 'allow';\n\n  /** Custom block message template.\n   *  Variables: {toolName}, {reason}, {agentRole}\n   *  @default 'Tool call blocked by AgentShield: {toolName} - {reason}'\n   */\n  blockMessage?: string;\n\n  /** Custom approval message template.\n   *  Variables: {toolName}, {reason}, {approvalRequestId}, {agentRole}\n   *  @default 'Tool call requires approval: {toolName} - {reason} (Request: {approvalRequestId})'\n   */\n  approvalMessage?: string;\n\n  /** Map LangChain tool names to AgentShield resource names.\n   *  e.g., { 'sql_db_query': 'PostgreSQL', 'requests_get': 'HTTPClient' }\n   */\n  toolNameMap?: Record<string, string>;\n\n  /** Map LangChain agent names to AgentShield agent roles.\n   *  e.g., { 'sql-agent': 'DataAgent' }\n   *  Checked against metadata/tags passed in handleToolStart.\n   */\n  agentRoleMap?: Record<string, string>;\n\n  /** Default agent role if none can be inferred.\n   *  @default 'DefaultAgent'\n   */\n  defaultAgentRole?: string;\n\n  /** Callback invoked after every evaluation.\n   *  Useful for logging, metrics, or custom side effects.\n   */\n  onEvaluate?: (event: AgentShieldEvent) => void;\n}\n```\n\n### Base Config (from AgentShield)\n\nThese fields are also available since `AgentShieldLangChainConfig` extends `AgentShieldConfig`:\n\n| Field | Type | Description |\n|---|---|---|\n| `mode` | `'hosted' \\| 'embedded'` | Operating mode (auto-detected if omitted) |\n| `serverUrl` | `string` | Server URL for hosted mode |\n| `apiKey` | `string` | API key for hosted mode |\n| `policies` | `Policy[]` | Initial policies for embedded mode |\n| `zeroTrust` | `boolean` | Default deny when no policy matches (default: `true`) |\n| `fetch` | `typeof fetch` | Custom fetch function (edge runtime, etc.) |\n\n## Tool Name Mapping\n\nMap LangChain tool names to the resource names used in your policies:\n\n```typescript\nconst handler = new AgentShieldCallbackHandler({\n  mode: 'embedded',\n  policies: [\n    {\n      policyId: 'POL-001',\n      name: 'Block SQL DROP',\n      agentRole: 'DataAgent',\n      resource: 'PostgreSQL',  // <-- policies reference this name\n      action: 'DROP',\n      permissionLevel: 'BLOCK',\n      priority: 20,\n      enabled: true,\n    },\n  ],\n  toolNameMap: {\n    'sql_db_query': 'PostgreSQL',       // LangChain tool -> AgentShield resource\n    'sql_db_schema': 'PostgreSQL',\n    'requests_get': 'HTTPClient',\n  },\n});\n```\n\n## Agent Role Mapping\n\nMap LangChain agent names to AgentShield roles using metadata or tags:\n\n```typescript\nconst handler = new AgentShieldCallbackHandler({\n  mode: 'embedded',\n  policies: [/* ... */],\n  agentRoleMap: {\n    'sql-agent': 'DataAgent',\n    'code-agent': 'CodeAgent',\n    'research-agent': 'ResearchAgent',\n  },\n  defaultAgentRole: 'DefaultAgent',\n});\n```\n\n## Evaluation Callback\n\nHook into every evaluation for logging, metrics, or side effects:\n\n```typescript\nconst handler = new AgentShieldCallbackHandler({\n  mode: 'embedded',\n  policies: [/* ... */],\n  onEvaluate: (event) => {\n    console.log(`[${event.result.decision}] ${event.agentRole} -> ${event.toolName}`);\n    // Send to your observability platform\n    metrics.increment(`agentshield.${event.result.decision.toLowerCase()}`);\n  },\n});\n```\n\nThe `AgentShieldEvent` object contains:\n\n| Field | Type | Description |\n|---|---|---|\n| `result` | `EvaluateResult` | The evaluation result from AgentShield |\n| `toolName` | `string` | The LangChain tool name |\n| `shieldResource` | `string` | The AgentShield resource name (after mapping) |\n| `agentRole` | `string` | The resolved agent role |\n| `args` | `Record<string, unknown>` | The arguments passed to the tool |\n| `timestamp` | `Date` | When the evaluation occurred |\n\n## Error Classes\n\n### `AgentShieldBlockError`\n\nThrown when a tool call is blocked and `onBlock` is `'throw'` (default).\n\n```typescript\nimport { AgentShieldBlockError } from '@agentshieldhq/langchain';\n\ntry {\n  // ... agent execution\n} catch (error) {\n  if (error instanceof AgentShieldBlockError) {\n    console.log(error.toolName);     // 'sql_db_query'\n    console.log(error.agentRole);    // 'DataAgent'\n    console.log(error.result);       // EvaluateResult object\n    console.log(error.result.reason); // 'Blocked by policy: Block SQL DROP'\n  }\n}\n```\n\nProperties:\n\n| Property | Type | Description |\n|---|---|---|\n| `result` | `EvaluateResult` | The evaluation result that caused the block |\n| `toolName` | `string` | The tool name that was blocked |\n| `agentRole` | `string` | The agent role that was blocked |\n\n### `AgentShieldApprovalError`\n\nThrown when a tool call requires approval and `onRequireApproval` is `'throw'` (default).\n\n```typescript\nimport { AgentShieldApprovalError } from '@agentshieldhq/langchain';\n\ntry {\n  // ... agent execution\n} catch (error) {\n  if (error instanceof AgentShieldApprovalError) {\n    console.log(error.toolName);                   // 'sql_db_query'\n    console.log(error.agentRole);                  // 'DataAgent'\n    console.log(error.result.approvalRequestId);   // 'APR-abc123'\n  }\n}\n```\n\nProperties:\n\n| Property | Type | Description |\n|---|---|---|\n| `result` | `EvaluateResult` | The evaluation result that triggered the approval |\n| `toolName` | `string` | The tool name that requires approval |\n| `agentRole` | `string` | The agent role that requires approval |\n\n## Utility Methods\n\n### `toCallbacks()`\n\nGet the handler as a plain callback object for LangChain compatibility:\n\n```typescript\nconst handler = new AgentShieldCallbackHandler({ /* ... */ });\n\n// Use as a plain object instead of class instance\nconst callbacks = handler.toCallbacks();\n```\n\n### `getShield()`\n\nAccess the underlying `AgentShield` instance for direct operations:\n\n```typescript\nconst handler = new AgentShieldCallbackHandler({\n  mode: 'embedded',\n  policies: [/* ... */],\n});\n\n// Add policies at runtime\nhandler.getShield().addPolicy({\n  policyId: 'POL-DYN',\n  name: 'Runtime policy',\n  agentRole: 'DataAgent',\n  resource: 'PostgreSQL',\n  action: 'DROP',\n  permissionLevel: 'BLOCK',\n  priority: 50,\n  enabled: true,\n});\n\n// Check health\nconst healthy = await handler.getShield().isHealthy();\n```\n\n## API Reference\n\n### `AgentShieldCallbackHandler`\n\nLangChain-compatible callback handler that intercepts tool calls and evaluates them through AgentShield.\n\n#### Constructor\n\n```typescript\nnew AgentShieldCallbackHandler(config?: AgentShieldLangChainConfig)\n```\n\nIf `mode` is not specified, it defaults to `'embedded'` unless `serverUrl` is provided.\n\n#### Callback Methods (LangChain Interface)\n\n| Method | Description |\n|---|---|\n| `handleToolStart(tool, input, runId?, parentRunId?, tags?, metadata?, kwargs?)` | Evaluates the tool call before execution |\n| `handleToolEnd(output, runId?, parentRunId?, tags?)` | Replaces output if the call was intercepted |\n| `handleToolError(error, runId?, parentRunId?, tags?)` | Cleans up interception state on error |\n\n#### Utility Methods\n\n| Method | Returns | Description |\n|---|---|---|\n| `toCallbacks()` | `Record<string, unknown>` | Get handler as a plain callback object |\n| `getShield()` | `AgentShield` | Access the underlying AgentShield instance |\n\n## Re-exported Types\n\nAll core types are re-exported for convenience:\n\n```typescript\nimport type {\n  Decision,\n  Policy,\n  PolicyDefinition,\n  EvaluateRequest,\n  EvaluateResult,\n  MatchedPolicy,\n  ConditionRule,\n  Trace,\n} from '@agentshieldhq/langchain';\n```\n\n## Related Packages\n\n- **[agentshield](https://www.npmjs.com/package/agentshield)** — Full SDK with hosted and embedded modes\n- **[@agentshieldhq/core](https://www.npmjs.com/package/@agentshieldhq/core)** — Low-level evaluation engine (used internally)\n\n## License\n\nMIT\n","readmeFilename":"README.md","_rev":"1-b47c243962227b6f9e238909b8689851"}