> This page is for Postman Docs, version Latest (v12) (default).
> For other versions, use one of these documentation indexes:
> - Latest (v12) (default): https://learning.postman.com/latest-v-12/llms.txt
> - v11: https://learning.postman.com/v11/llms.txt

> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://learning.postman.com/llms.txt.

# Write scripts and tests for MCP requests

> Add scripts to Model Context Protocol (MCP) requests to set up a connection, test what a server exposes, and test every tool call, prompt, and resource read.

You can add scripts to your [Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) requests to set up a connection, test what a server exposes, and test every tool call, prompt, and resource read. Scripts run in the [Postman Sandbox](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/overview/), so you can use the `pm` object, variables, the Postman Vault, `pm.sendRequest`, and package library imports, the same as in HTTP scripts.

Use scripts with MCP requests to do the following:

* Set the server URL, headers, or command before Postman connects.
* Check the server's name, protocol version, and capabilities.
* Check that the server exposes the tools, prompts, and resources you expect, with the input schemas you expect.
* Test the result of each call and save values for later calls.
* Clean up tokens and IDs when the session ends.
* Run MCP requests in the [Collection Runner](/docs/tests-and-scripts/running-collections/intro-to-collection-runs/) next to HTTP and other requests.

## How MCP scripts run

An MCP request is a session: Postman connects to the server, you send one or more calls, and then Postman disconnects. Scripts attach to four points in that session, called *hooks*. They run in this order:

| Hook                 | When it runs                                                                                              | How often           | Use it to                                                            |
| -------------------- | --------------------------------------------------------------------------------------------------------- | ------------------- | -------------------------------------------------------------------- |
| **Before connect**   | Before the client connects to the server                                                                  | Once per connection | Set the URL, headers, authentication, or command for the connection. |
| **After connect**    | When the server is ready, after initialization and the first listing of its tools, prompts, and resources | Once per connection | Test the server's identity, capabilities, and what it exposes.       |
| **After response**   | When a tool call, prompt, or resource read returns a result or an error                                   | After every call    | Test the response and save values for later calls.                   |
| **After disconnect** | After the client disconnects from the server                                                              | Once per connection | Clear values the session set, such as tokens or IDs.                 |

Keep the following in mind about when scripts run:

* Postman reads the request's current scripts on every call. If you edit an **After response** script while you're connected, the change applies to the next call. You don't need to reconnect.
* When you enter a URL or command and Postman loads the server's tools, prompts, and resources for you, no connection scripts run. Connection scripts run when you click **Connect** or send a call.
* If you call `pm.execution.skipRequest()` in a **Before connect** script, Postman doesn't connect to the server. No later scripts run. If a **Before connect** script fails, Postman also doesn't connect.
* **After response** scripts run after each tool call, prompt, and resource read that you send. They don't run for calls made by MCP Apps.
* **After disconnect** scripts run after a disconnect that the client asked for.
* `pm.sendRequest` always sends an HTTP request, even in a script for an MCP request. To learn more, see [pm.sendRequest](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-send-request/).
* In `pm.info.eventName`, the hooks are `beforeConnect`, `afterConnect`, `afterResponse`, and `afterDisconnect`. To learn more, see [pm.info](/docs/tests-and-scripts/write-scripts/postman-sandbox-reference/pm-info/).

## Add a script to an MCP request

To add a script to an MCP request, do the following:

1. Open an MCP request.
2. Click the **Scripts** tab.
3. Select a hook: **Before connect**, **After connect**, **After response**, or **After disconnect**.
4. Write your script in the editor, or select a snippet from the snippets list.
5. Save the request.

The snippets for MCP requests include the following:

* Set an `Authorization` header.
* Test the server name and protocol version.
* Test that tools are exposed.
* Test a tool's input schema.
* Test that a call succeeded or reported an error.
* Test structured content.
* Test response time.

## The pm object in MCP scripts

The values of `pm.request` and `pm.response` depend on the hook:

| Hook                 | `pm.request`                                                                      | `pm.response`                                                                                      |
| -------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| **Before connect**   | The connection that's about to open. Change it to change what connects.           | Not available.                                                                                     |
| **After connect**    | The connection as it was opened.                                                  | The ready server: its handshake, and every tool, prompt, resource, and resource template it lists. |
| **After response**   | The call as it was sent.                                                          | The call's result, or the error it failed with.                                                    |
| **After disconnect** | The connection the session opened, including any changes from **Before connect**. | Not available.                                                                                     |

### Connection properties

In **Before connect**, **After connect**, and **After disconnect**, `pm.request` describes the connection:

| Property                 | Description                                                     |
| ------------------------ | --------------------------------------------------------------- |
| `transport`              | `'sse'` for HTTP servers or `'stdio'` for local servers.        |
| `url`                    | The server URL (HTTP).                                          |
| `headers`                | An array of `{ key, value }` headers (HTTP).                    |
| `command`, `args`, `env` | The command, arguments, and environment variables (STDIO).      |
| `settings`               | `version`, `strictSSL`, `requestTimeout`, and `sessionTimeout`. |

### Server properties

In **After connect**, `pm.response` describes the server:

| Property                                             | Description                                                                                                                                |
| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `server`                                             | The server's `name`, `version`, and `title`.                                                                                               |
| `protocolVersion`                                    | The MCP protocol version Postman and the server agreed on.                                                                                 |
| `capabilities`                                       | The capabilities the server declared.                                                                                                      |
| `instructions`                                       | The server's instructions, if it sent any.                                                                                                 |
| `tools`, `prompts`, `resources`, `resourceTemplates` | Everything the server lists. Each tool includes its `inputSchema`, and its `outputSchema` and `annotations` when the server provides them. |
| `failures`                                           | Any list request that failed, keyed by `tools`, `prompts`, `resources`, or `resourceTemplates`.                                            |
| `error`, `responseTime`                              | The connection error, if any, and how long the connection took.                                                                            |

### Call properties

In **After response**, `pm.request` and `pm.response` describe the call:

| Property                   | Description                                                                                                                               |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `pm.request.method`        | `'tools/call'`, `'prompts/get'`, or `'resources/read'`.                                                                                   |
| `pm.request.params`        | The `name` or `uri`, and the `arguments` you sent.                                                                                        |
| `pm.response.result`       | The result. Tool calls return `content`, `structuredContent`, and `isError`. Prompts return `messages`. Resource reads return `contents`. |
| `pm.response.error`        | The error the call failed with, including its `kind` (`transport`, `protocol`, `auth`, or `timeout`), `code`, and `message`.              |
| `pm.response.responseTime` | How long the call took, in milliseconds.                                                                                                  |

## Examples

### Set an authorization header before connecting

```js
// Before connect
pm.request.headers = pm.request.headers || [];
pm.request.headers.push({
  key: 'Authorization',
  value: `Bearer ${pm.environment.get('token')}`,
});
```

### Test what the server exposes

```js
// After connect
pm.test('Connected to the expected server', function () {
  pm.expect(pm.response.server.name).to.eql('weather-server');
});

pm.test('Exposes the required tools', function () {
  pm.expect(pm.response.tools.map((tool) => tool.name)).to.include.members([
    'get_forecast',
  ]);
});

pm.test('get_forecast requires a city', function () {
  const tool = pm.response.tools.find((tool) => tool.name === 'get_forecast');
  pm.expect(tool.inputSchema.required).to.include('city');
});

pm.test('Every capability was listed', function () {
  pm.expect(pm.response.failures).to.be.empty;
});
```

### Test one tool's response

An **After response** script runs after every call in the session. To test a single tool, check the method and name first:

```js
// After response
if (pm.request.method === 'tools/call' && pm.request.params.name === 'get_forecast') {
  pm.test('get_forecast succeeded', function () {
    pm.expect(pm.response.error).to.be.undefined;
    pm.expect(pm.response.result.isError).not.to.eql(true);
  });

  pm.test('Result has a temperature', function () {
    pm.expect(pm.response.result.structuredContent).to.have.property('temperature');
  });
}
```

### Save a value for the next call

```js
// After response
if (pm.request.params.name === 'create_ticket') {
  const { ticketId } = pm.response.result.structuredContent;
  pm.environment.set('ticketId', ticketId);
}
```

Use `{{ticketId}}` in the arguments of the next call.

### Clean up when the session ends

```js
// After disconnect
pm.environment.unset('ticketId');
```

## View test results

Test results appear in the **Test Results** tab in the response pane. Postman groups the session's tests as follows:

* **Connection** for tests in **After connect**.
* One group per call, labeled with the tool name and its first argument.
* **Disconnection** for tests in **After disconnect**.

## Add MCP scripts to a collection or folder

Collection and folder scripts run for every MCP request inside them. Use them to set authentication once, or to run the same checks against every server in a collection.

To add MCP scripts to a collection or folder, do the following:

1. Open the collection or folder and click the **Scripts** tab.
2. Select an MCP hook. MCP hooks have an `mcp:` prefix: `mcp:beforeConnect`, `mcp:afterConnect`, `mcp:afterResponse`, and `mcp:afterDisconnect`.
3. Write your script and save.

MCP hooks run only for MCP requests. HTTP and other request types in the same collection keep using their own hooks.

## Run MCP requests in the Collection Runner

The Collection Runner runs MCP requests with their scripts and tests, in the same run as HTTP and other request types. Values you set in one request's scripts are available to the requests that follow, so a single run can call an API and then check the MCP tool that depends on it.

A STDIO MCP server starts a process on your machine. Before you can run a STDIO request in the Collection Runner, you must approve it from the request first. The run won't start until you approve every STDIO request in the run.

To learn more, see [Run collections](/docs/tests-and-scripts/running-collections/intro-to-collection-runs/).

## Run MCP scripts and tests from the command line

You can also run MCP requests with their scripts and tests using the Postman CLI. To learn more, see [Postman CLI MCP commands](/docs/postman-cli/postman-cli-mcp/) and [Run a collection with the Postman CLI](/docs/postman-cli/postman-cli-run-collection/).