Skip to content

TypeScript MCP Server

Generate a TypeScript Model Context Protocol (MCP) server for providing context to Large Language Models (LLMs), and optionally deploy it to Amazon Bedrock AgentCore.

The Model Context Protocol (MCP) is an open standard that allows AI assistants to interact with external tools and resources. It provides a consistent way for LLMs to:

  • Execute tools (functions) that perform actions or retrieve information
  • Access resources that provide context or data

You can generate a TypeScript MCP server in two ways:

  1. Install the Nx Console VSCode Plugin if you haven't already
  2. Open the Nx Console in VSCode
  3. Click Generate (UI) in the "Common Nx Commands" section
  4. Search for @aws/nx-plugin - ts#mcp-server
  5. Fill in the required parameters
    • Click Generate
    Parameter Type Default Description
    project Required string - The project to add an MCP server to
    computeType string BedrockAgentCoreRuntime The type of compute to host your MCP server. Select None for no hosting.
    name string - The name of your MCP server (default: mcp-server)
    iacProvider string CDK The preferred IaC provider

    The generator will add the following files to your existing TypeScript project:

    • Directoryyour-project/
      • Directorysrc/
        • Directorymcp-server/ (or custom name if specified)
          • index.ts Exports your server
          • server.ts Main server definition
          • stdio.ts Entry point for STDIO transport, useful for simple local MCP servers
          • http.ts Entry point for Streamable HTTP transport, useful for hosting your MCP server
          • Directorytools/
            • add.ts Sample tool
          • Directoryresources/
            • sample-guidance.ts Sample resource
          • Dockerfile Entry point for hosting your MCP server (excluded when computeType is set to None)
      • package.json Updated with bin entry and MCP dependencies
      • project.json Updated with MCP server serve target

    Since this generator vends infrastructure as code based on your chosen iacProvider, it will create a project in packages/common which includes the relevant CDK constructs or Terraform modules.

    The common infrastructure as code project is structured as follows:

    • Directorypackages/common/constructs
      • Directorysrc
        • Directoryapp/ Constructs for infrastructure specific to a project/generator
        • Directorycore/ Generic constructs which are reused by constructs in app
        • index.ts Entry point exporting constructs from app
      • project.json Project build targets and configuration

    For deploying your MCP Server, the following files are generated:

    • Directorypackages/common/constructs/src
      • Directoryapp
        • Directorymcp-servers
          • Directory<project-name>
            • <project-name>.ts CDK construct for deploying your MCP Server
            • Dockerfile Passthrough docker file used by the CDK construct
      • Directorycore
        • Directoryagent-core
          • runtime.ts Generic CDK construct for deploying to Bedrock AgentCore Runtime

    Tools are functions that the AI assistant can call to perform actions. You can add new tools in the server.ts file:

    server.tool("toolName", "tool description",
    { param1: z.string(), param2: z.number() }, // Input schema using Zod
    async ({ param1, param2 }) => {
    // Tool implementation
    return {
    content: [{ type: "text", text: "Result" }]
    };
    }
    );

    Resources provide context to the AI assistant. You can add static resources from files or dynamic resources:

    const exampleContext = 'some context to return';
    server.resource('resource-name', 'example://resource', async (uri) => ({
    contents: [{ uri: uri.href, text: exampleContext }],
    }));
    // Dynamic resource
    server.resource('dynamic-resource', 'dynamic://resource', async (uri) => {
    const data = await fetchSomeData();
    return {
    contents: [{ uri: uri.href, text: data }],
    };
    });

    Most AI assistants that support MCP use a similar configuration approach. You’ll need to create or update a configuration file with your MCP server details:

    {
    "mcpServers": {
    "your-mcp-server": {
    "command": "npx",
    "args": ["tsx", "/path/to/your-mcp-server/stdio.ts"]
    }
    }
    }

    While developing your MCP server, you may wish to configure the --watch flag so that the AI assistant always sees the latest versions of tools/resources:

    {
    "mcpServers": {
    "your-mcp-server": {
    "command": "npx",
    "args": ["tsx", "--watch", "/path/to/your-mcp-server/stdio.ts"]
    }
    }
    }

    Please refer to the following documentation for configuring MCP with specific AI Assistants:

    The generator configures a target named <your-server-name>-inspect, which starts the MCP Inspector with the configuration to connect to your MCP server using STDIO transport.

    Terminal window
    pnpm nx run your-project:your-server-name-inspect

    This will start the inspector at http://localhost:6274. Get started by clicking on the “Connect” button.

    The easiest way to test and use an MCP server is by using the inspector or configuring it with an AI assistant (as above).

    You can however run your server with STDIO transport directly using the <your-server-name>-serve-stdio target.

    Terminal window
    pnpm nx run your-project:your-server-name-serve-stdio

    This command uses tsx --watch to automatically restart the server when files change.

    If you would like to run your MCP server locally using Streamable HTTP transport, you can use the <your-server-name>-serve-http target.

    Terminal window
    pnpm nx run your-project:your-server-name-serve-http

    This command uses tsx --watch to automatically restart the server when files change.

    Deploying Your MCP Server to Bedrock AgentCore Runtime

    Section titled “Deploying Your MCP Server to Bedrock AgentCore Runtime”

    If you selected BedrockAgentCoreRuntime for computeType, the relevant CDK or Terraform infrastructure is generated which you can use to deploy your MCP server to Amazon Bedrock AgentCore Runtime.

    A CDK construct is generated for your, named based on the name you chose when running the generator, or <ProjectName>McpServer by default.

    You can use this CDK construct in a CDK application:

    import { MyProjectMcpServer } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    // Add the MCP server to your stack
    new MyProjectMcpServer(this, 'MyProjectMcpServer');
    }
    }

    By default, your MCP server will be secured using IAM authentication, simply deploy it without any arguments:

    import { MyProjectMcpServer } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    new MyProjectMcpServer(this, 'MyProjectMcpServer');
    }
    }

    You can grant access to invoke your MCP on Bedrock AgentCore Runtime using the grantInvoke method. For example you may wish for an agent generated with the py#strands-agent generator to call your MCP server:

    import { MyProjectAgent, MyProjectMcpServer } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    const agent = new MyProjectAgent(this, 'MyProjectAgent');
    const mcpServer = new MyProjectMcpServer(this, 'MyProjectMcpServer');
    mcpServer.agentCoreRuntime.grantInvoke(agent.agentCoreRuntime);
    }
    }

    The below demonstrates how to configure Cognito authentication for your agent.

    To configure JWT authentication, you can pass the authorizerConfiguration property to your MCP server construct. Here is an example which configures a Cognito user pool and client to secure the MCP server:

    import { MyProjectMcpServer } from ':my-scope/common-constructs';
    export class ExampleStack extends Stack {
    constructor(scope: Construct, id: string) {
    const userPool = new UserPool(this, 'UserPool');
    const client = userPool.addClient('Client', {
    authFlows: {
    userPassword: true,
    },
    });
    new MyProjectMcpServer(this, 'MyProjectMcpServer', {
    authorizerConfiguration: {
    customJWTAuthorizer: {
    discoveryUrl: `https://cognito-idp.${Stack.of(userPool).region}.amazonaws.com/${userPool.userPoolId}/.well-known/openid-configuration`,
    allowedClients: [client.userPoolClientId],
    },
    },
    });
    }
    }

    In order to build your MCP server for Bedrock AgentCore Runtime, a <your-mcp-server>-bundle target is added to your project, which:

    • Bundles your MCP server into a single JavaScript file with esbuild, using http.ts as the entrypoint for a Streamable HTTP MCP server.
    • Builds a docker image from the Dockerfile which runs this bundled server on port 8000, as per the MCP protocol contract

    Your MCP server is automatically configured with observability using the AWS Distro for Open Telemetry (ADOT), by configuring auto-instrumentation in your Dockerfile.

    You can find traces in the CloudWatch AWS Console, by selecting “GenAI Observability” in the menu. Note that for traces to be populated you will need to enable Transaction Search.

    For more details, refer to the AgentCore documentation on observability.