> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-5e9cc07a-preview-contex-1789468204-c45d5ed.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Add custom middleware to Managed Deep Agents

> Add built-in or custom middleware to a managed deep agent.

Middleware adds behavior around model calls, tool calls, and the agent lifecycle. Like [custom tools](/langsmith/javascript/managed-deep-agents-tools), MDA does not discover middleware automatically. Import it and pass it to the agent definition.

<Note>
  Managed Deep Agents is in **public [beta](/langsmith/release-stages)** and available on [LangSmith Cloud](/langsmith/cloud) in the US region only.
</Note>

Put custom middleware under `middleware/`, import it into the agent entry, and pass it to the agent definition:

```text theme={null}
my-agent/
  agent.ts
  middleware/
    audit.ts
```

For the full project layout, see [Project structure](/langsmith/javascript/managed-deep-agents-project-structure).

The managed runtime still owns `backend`, `store`, `checkpointer`, `memory`, `skills`, and the system prompt. Middleware should focus on agent behavior around model calls, tool calls, and lifecycle hooks.

## Add middleware

Use middleware to redact PII, enforce call limits, retry failures, fall back between models, select models dynamically, or log and inspect tool calls.

<Steps>
  <Step title="Use prebuilt middleware" id="use-prebuilt-middleware">
    You can use LangChain [prebuilt middleware](/oss/javascript/langchain/middleware/built-in) directly in the agent definition:

    ```ts agent.ts theme={null}
    import { defineDeepAgent } from "managed-deepagents";
    import { modelCallLimitMiddleware, piiMiddleware } from "langchain";

    export const agent = defineDeepAgent({
      name: "support-agent",
      model: "openai:gpt-5.5",
      middleware: [
        piiMiddleware("email", { strategy: "redact", applyToInput: true }),
        modelCallLimitMiddleware({ runLimit: 50 }),
      ],
    });
    ```
  </Step>

  <Step title="Define custom middleware (Optional)" id="define-custom-middleware">
    For a more advanced option, define [custom middleware](/oss/javascript/langchain/middleware/custom) in a local module.

    ```ts middleware/audit.ts theme={null}
    import { createMiddleware } from "langchain";

    export const logToolCalls = createMiddleware({
      name: "LogToolCalls",
      wrapToolCall: async (request, handler) => {
        console.log(`Calling tool: ${request.toolCall.name}`);
        const result = await handler(request);
        console.log(`Finished tool: ${request.toolCall.name}`);
        return result;
      },
    });
    ```

    Import the middleware into the project-root agent entry and pass it in the `middleware` list:

    ```ts agent.ts theme={null}
    import { defineDeepAgent } from "managed-deepagents";

    import { logToolCalls } from "./middleware/audit";

    export const agent = defineDeepAgent({
      name: "support-agent",
      model: "openai:gpt-5.5",
      middleware: [logToolCalls],
    });
    ```

    Your middleware imports should work the same way they do in a normal local TypeScript project.
  </Step>
</Steps>

## Use runtime context

Middleware can read per-run context through the normal LangChain runtime APIs. Use context for user IDs, organization IDs, feature flags, request metadata, or credentials that should not be part of the model prompt by default.

For examples, see [Custom middleware](/oss/javascript/langchain/middleware/custom).

## Deployment

`mda dev` and `mda deploy` copy project files into the compiled build, including modules under `middleware/`. Middleware is not synced to Context Hub; it ships with the agent code.

## When to use middleware

| Concept                                                                    | Kind             | How it reaches the agent                |
| -------------------------------------------------------------------------- | ---------------- | --------------------------------------- |
| **Middleware**                                                             | Application code | Import and pass in the agent definition |
| **[Custom tools](/langsmith/javascript/managed-deep-agents-tools)**        | Application code | Import and pass in the agent definition |
| **[Instructions](/langsmith/javascript/managed-deep-agents-instructions)** | Managed context  | Always-on system prompt                 |

For more information, see [Project structure](/langsmith/javascript/managed-deep-agents-project-structure).

***

<div className="source-links">
  <Callout icon="terminal-2">
    [Connect these docs](/use-these-docs) to Claude, VSCode, and more via MCP for real-time answers.
  </Callout>

  <Callout icon="edit">
    [Edit this page on GitHub](https://github.com/langchain-ai/docs/edit/main/src/langsmith/managed-deep-agents-middleware.mdx) or [file an issue](https://github.com/langchain-ai/docs/issues/new/choose).
  </Callout>
</div>
