Skip to navigation

Write scripts and tests for MCP requests

View as Markdown

You can add scripts to your Model Context Protocol (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, 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 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:

HookWhen it runsHow oftenUse it to
Before connectBefore the client connects to the serverOnce per connectionSet the URL, headers, authentication, or command for the connection.
After connectWhen the server is ready, after initialization and the first listing of its tools, prompts, and resourcesOnce per connectionTest the server’s identity, capabilities, and what it exposes.
After responseWhen a tool call, prompt, or resource read returns a result or an errorAfter every callTest the response and save values for later calls.
After disconnectAfter the client disconnects from the serverOnce per connectionClear 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.
  • In pm.info.eventName, the hooks are beforeConnect, afterConnect, afterResponse, and afterDisconnect. To learn more, see 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:

Hookpm.requestpm.response
Before connectThe connection that’s about to open. Change it to change what connects.Not available.
After connectThe connection as it was opened.The ready server: its handshake, and every tool, prompt, resource, and resource template it lists.
After responseThe call as it was sent.The call’s result, or the error it failed with.
After disconnectThe 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:

PropertyDescription
transport'sse' for HTTP servers or 'stdio' for local servers.
urlThe server URL (HTTP).
headersAn array of { key, value } headers (HTTP).
command, args, envThe command, arguments, and environment variables (STDIO).
settingsversion, strictSSL, requestTimeout, and sessionTimeout.

Server properties

In After connect, pm.response describes the server:

PropertyDescription
serverThe server’s name, version, and title.
protocolVersionThe MCP protocol version Postman and the server agreed on.
capabilitiesThe capabilities the server declared.
instructionsThe server’s instructions, if it sent any.
tools, prompts, resources, resourceTemplatesEverything the server lists. Each tool includes its inputSchema, and its outputSchema and annotations when the server provides them.
failuresAny list request that failed, keyed by tools, prompts, resources, or resourceTemplates.
error, responseTimeThe connection error, if any, and how long the connection took.

Call properties

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

PropertyDescription
pm.request.method'tools/call', 'prompts/get', or 'resources/read'.
pm.request.paramsThe name or uri, and the arguments you sent.
pm.response.resultThe result. Tool calls return content, structuredContent, and isError. Prompts return messages. Resource reads return contents.
pm.response.errorThe error the call failed with, including its kind (transport, protocol, auth, or timeout), code, and message.
pm.response.responseTimeHow long the call took, in milliseconds.

Examples

Set an authorization header before connecting

// 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

// 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:

// 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

// 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

// 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.

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 and Run a collection with the Postman CLI.