Skip to content

Your First MCP Server in TypeScript: Tools, Resources, and Prompts

Build a small, production-minded MCP server in TypeScript, then take it from local development through AWS deployment, testing, observability, and recovery.

Ekanatha Reddy Urivakili18 min3,411 words

1. Context and scale

MCP gives an AI application a standard way to discover and use capabilities exposed by a server. The useful starting point is not a general-purpose agent platform. It is a small service that exposes a few well-defined tools, resources, and prompts over the Model Context Protocol.

This blueprint builds an issue-triage server for a small product team. An MCP client can find open issues in a project, read a project overview, and retrieve a prompt template for triaging an issue. The server does not make changes to the issue tracker. Read-only behavior keeps the first deployment simple and limits the consequences of a client mistake.

The implementation uses TypeScript, the official MCP TypeScript SDK, PostgreSQL, and AWS. Developers can run the server locally over stdio. The deployed server uses Streamable HTTP behind an Application Load Balancer. The production version authenticates users with OAuth access tokens and scopes every database query to the authenticated user.

This is a small-service design, not a universal MCP platform. One team owns the API, database, deployment, and operations.

AssumptionPlanning value
Users30 named users, fewer than 1,000 daily users
Requests0.2 average MCP requests/s; brief peaks below 5 requests/s
Data volume10 GB PostgreSQL data, including indexes and growth headroom
Team size2 engineers
BudgetTarget below $200/month before tax; estimate validated against the deployment region
AvailabilitySingle AWS region; no multi-region failover
WorkloadRead-heavy issue lookup, project overview, and prompt retrieval

These are sizing assumptions, not capacity guarantees. The first deployment should measure request shape, database latency, and actual token use before anyone treats the assumptions as requirements.

2. Requirements

The key design choice is to keep the MCP contract small and explicit. Tools are callable operations, resources are addressable context, and prompts are reusable message templates. None of those is a substitute for authorization.

Functional requirements

IDRequirementMCP surface
F1Find open issues for a project, with a bounded result countTool
F2Read an overview for a project the user is allowed to accessResource
F3Provide a consistent issue-triage instruction templatePrompt
F4Authenticate remote users and scope data to their identityHTTP authorization and database predicates
F5Support local development through a stdio MCP serverstdio transport

Non-functional requirements

IDRequirementInitial target
N1Avoid cross-user data accessEvery database read is scoped to the verified user
N2Keep service operations smallOne stateless application service and one managed database
N3Make failures diagnosableStructured logs, traces, service metrics, and database metrics
N4Keep responses boundedValidate inputs and cap tool results
N5Recover from routine application and database failureHealth checks, backups, tested restore instructions
N6Preserve a clear expansion pathAdd capacity or separate components only in response to measured limits

3. High-level design

The MCP client sends protocol requests to the server. The server authenticates the request, invokes a registered tool, resource, or prompt handler, and returns a protocol response. PostgreSQL stores projects and issues. Cognito provides the OAuth identity integration; application code verifies access tokens before creating a request-scoped MCP server.

flowchart LR
    Client["MCP client"] --> Cognito["Amazon Cognito"]
    Client --> Alb["Application Load Balancer"]
    Alb --> App["Amazon ECS Fargate"]
    App --> Db["Amazon RDS for PostgreSQL"]
    App --> Logs["Amazon CloudWatch"]
    App --> Secrets["AWS Secrets Manager"]
    Ecr["Amazon ECR"] --> App

Caption: A single-region AWS deployment with a managed PostgreSQL database and one small application service.

Keep the deployed server stateless: the application does not keep conversation state or MCP session state in process memory. This allows the service to be replaced or restarted without losing application data. It also avoids introducing Redis or a second persistence layer before a measured requirement exists.

For HTTP, use Streamable HTTP rather than inventing a custom JSON endpoint. This blueprint uses stateless request handling: the server creates an MCP server and transport for each authenticated protocol request. That suits the small, read-oriented workload and avoids sticky sessions. It is not a universal choice; features that depend on persistent server-initiated messages may require a different session strategy.

The local stdio process is deliberately a separate entry point. It is useful for development and for clients that launch a local server, but it is not a reason to expose a production container’s standard input as a network interface.

4. Cloud service mapping

AWS is the primary deployment target. The equivalents below are service categories, not claims that each provider’s service has identical behavior or pricing.

ComponentAWS choiceAzure equivalentGCP equivalent
Container runtimeAmazon ECS on AWS FargateAzure Container AppsCloud Run
HTTP entry pointApplication Load BalancerAzure Application GatewayCloud Load Balancing
Relational databaseAmazon RDS for PostgreSQLAzure Database for PostgreSQLCloud SQL for PostgreSQL
OAuth identityAmazon CognitoMicrosoft Entra IDIdentity Platform
Container registryAmazon ECRAzure Container RegistryArtifact Registry
SecretsAWS Secrets ManagerAzure Key VaultSecret Manager
Logs and metricsAmazon CloudWatchAzure MonitorCloud Monitoring and Cloud Logging
NetworkAmazon VPCAzure Virtual NetworkVirtual Private Cloud

A single Fargate service avoids managing a Kubernetes cluster for a service with one small team and one deployable. RDS avoids maintaining database backups and patching the database host. The trade-off is provider-specific infrastructure and a higher fixed monthly floor than running everything on one virtual machine.

5. Data design

The database holds the minimum data required by the server: users, projects, project membership, and issues. The authorization boundary is represented in the model so that access checks are visible in queries rather than being an informal convention in handlers.

The MCP server does not store prompts as executable code or infer access from a project identifier. A client-provided identifier is an input to a query, not proof that the caller may read that project.

erDiagram
    APP_USER ||--o{ PROJECT_MEMBER : joins
    PROJECT ||--o{ PROJECT_MEMBER : grants
    PROJECT ||--o{ ISSUE : contains
    APP_USER {
        uuid id PK
        text cognito_sub UK
    }
    PROJECT {
        uuid id PK
        text name
    }
    PROJECT_MEMBER {
        uuid project_id PK
        uuid user_id PK
    }
    ISSUE {
        uuid id PK
        uuid project_id FK
        text title
        text status
        timestamptz updated_at
    }

Caption: Membership is an explicit relationship used to scope project and issue reads.

CREATE TABLE app_user (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    cognito_sub text NOT NULL UNIQUE
);

CREATE TABLE project (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    name text NOT NULL CHECK (length(name) BETWEEN 1 AND 160),
    created_at timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE project_member (
    project_id uuid NOT NULL REFERENCES project(id) ON DELETE CASCADE,
    user_id uuid NOT NULL REFERENCES app_user(id) ON DELETE CASCADE,
    PRIMARY KEY (project_id, user_id)
);

CREATE TABLE issue (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    project_id uuid NOT NULL REFERENCES project(id) ON DELETE CASCADE,
    title text NOT NULL CHECK (length(title) BETWEEN 1 AND 500),
    status text NOT NULL CHECK (status IN ('open', 'in_progress', 'closed')),
    updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX issue_project_status_updated_idx
    ON issue (project_id, status, updated_at DESC);

CREATE INDEX project_member_user_project_idx
    ON project_member (user_id, project_id);

The tool query joins through membership and filters by the authenticated user’s database identity. A production migration should create the database user, seed or synchronize identity mappings, and apply schema changes through a controlled migration step. Do not let the application role create tables or alter schemas.

6. Low-level design

Keep protocol registration separate from database access. A small service layer makes the access rule testable without an MCP client, while the MCP registration layer converts validated protocol inputs into service calls and protocol results.

classDiagram
    class McpServer {
        +registerTool()
        +registerResource()
        +registerPrompt()
    }
    class IssueService {
        +findOpenIssues(userId, projectId, limit)
        +getProjectOverview(userId, projectId)
    }
    class IssueRepository {
        +findOpenIssues(userId, projectId, limit)
        +getProjectOverview(userId, projectId)
    }
    class PgIssueRepository {
        +findOpenIssues(userId, projectId, limit)
        +getProjectOverview(userId, projectId)
    }
    class Principal {
        +userId
        +subject
    }
    McpServer --> IssueService
    IssueService --> IssueRepository
    IssueRepository <|.. PgIssueRepository
    McpServer --> Principal

Caption: Protocol handlers depend on a narrow service abstraction; the repository owns scoped SQL.

Minimal runnable example: stdio

Create a TypeScript project, install @modelcontextprotocol/sdk and zod, then run this file with a TypeScript runner such as tsx. It exposes a single local tool and writes protocol traffic over stdio.

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "first-mcp-server",
  version: "1.0.0",
});

server.registerTool(
  "add",
  {
    description: "Add two numbers.",
    inputSchema: { a: z.number(), b: z.number() },
  },
  async ({ a, b }) => ({
    content: [{ type: "text", text: String(a + b) }],
  }),
);

await server.connect(new StdioServerTransport());

What to notice: the MCP SDK owns protocol framing; do not write diagnostic output to stdout in a stdio server.

Realistic runnable example: stateless HTTP server

This example uses Express, PostgreSQL, Cognito JWT verification, and the SDK’s Streamable HTTP transport. Install express, pg, zod, @aws-jwt-verify/cognito-verifier, and the MCP SDK. Configure the Cognito user pool and client ID through environment variables. The database schema is the one shown above.

import express from "express";
import pg from "pg";
import { CognitoJwtVerifier } from "aws-jwt-verify";
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";

const { Pool } = pg;
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

const verifier = CognitoJwtVerifier.create({
  userPoolId: process.env.COGNITO_USER_POOL_ID!,
  tokenUse: "access",
  clientId: process.env.COGNITO_CLIENT_ID!,
});

type Principal = { subject: string; userId: string };

async function createMcpServer(principal: Principal) {
  const server = new McpServer({ name: "issue-triage", version: "1.0.0" });

  server.registerTool(
    "find-open-issues",
    {
      description: "Find open issues in a project the caller can access.",
      inputSchema: {
        projectId: z.string().uuid(),
        limit: z.number().int().min(1).max(50).default(10),
      },
    },
    async ({ projectId, limit }) => {
      const result = await pool.query(
        `SELECT i.id, i.title, i.updated_at
           FROM issue i
           JOIN project_member pm ON pm.project_id = i.project_id
           JOIN app_user u ON u.id = pm.user_id
          WHERE u.cognito_sub = $1
            AND i.project_id = $2
            AND i.status = 'open'
          ORDER BY i.updated_at DESC
          LIMIT $3`,
        [principal.subject, projectId, limit],
      );

      return {
        content: [{ type: "text", text: JSON.stringify(result.rows) }],
      };
    },
  );

  server.registerResource(
    "project-overview",
    new ResourceTemplate("project://{projectId}/overview", { list: undefined }),
    { description: "Project name and issue counts.", mimeType: "application/json" },
    async (uri, variables) => {
      const result = await pool.query(
        `SELECT p.id, p.name,
                count(i.id) FILTER (WHERE i.status = 'open') AS open_issues,
                count(i.id) FILTER (WHERE i.status = 'in_progress') AS in_progress_issues
           FROM project p
           JOIN project_member pm ON pm.project_id = p.id
           JOIN app_user u ON u.id = pm.user_id
           LEFT JOIN issue i ON i.project_id = p.id
          WHERE u.cognito_sub = $1 AND p.id = $2
          GROUP BY p.id, p.name`,
        [principal.subject, variables.projectId],
      );

      if (result.rowCount === 0) {
        return { contents: [] };
      }

      return {
        contents: [{
          uri: uri.href,
          mimeType: "application/json",
          text: JSON.stringify(result.rows[0]),
        }],
      };
    },
  );

  server.registerPrompt(
    "triage-issue",
    {
      description: "Create a concise issue-triage request.",
      argsSchema: {
        issue: z.string().min(1).max(2000),
        context: z.string().max(2000).optional(),
      },
    },
    ({ issue, context }) => ({
      messages: [{
        role: "user",
        content: {
          type: "text",
          text: `Triage this issue. Identify likely impact, missing information, and a safe next step.\n\nIssue: ${issue}\n\nContext: ${context ?? "None provided"}`,
        },
      }],
    }),
  );

  return server;
}

const app = express();
app.use(express.json({ limit: "64kb" }));

app.post("/mcp", async (req, res) => {
  const authorization = req.header("authorization");
  const match = authorization?.match(/^Bearer\s+(.+)$/i);
  if (!match) {
    res.status(401).json({ error: "Bearer token required" });
    return;
  }

  try {
    const claims = await verifier.verify(match[1]);
    const user = await pool.query(
      "SELECT id FROM app_user WHERE cognito_sub = $1",
      [claims.sub],
    );
    if (user.rowCount !== 1) {
      res.status(403).json({ error: "User is not provisioned" });
      return;
    }

    const server = await createMcpServer({
      subject: claims.sub,
      userId: user.rows[0].id,
    });
    const transport = new StreamableHTTPServerTransport({
      sessionIdGenerator: undefined,
    });

    await server.connect(transport);
    await transport.handleRequest(req, res, req.body);
  } catch {
    if (!res.headersSent) {
      res.status(401).json({ error: "Invalid request or access token" });
    } else {
      res.destroy();
    }
  }
});

app.listen(Number(process.env.PORT ?? 3000), "0.0.0.0");

What to notice: the tool never accepts a user ID from the client, and both SQL reads derive permission from the verified subject. The prompt is a template, not an instruction to execute a side effect.

Before deploying, verify the SDK API against the installed SDK version, add protocol error handling and request logging, and implement the OAuth protected-resource metadata required by your MCP client. The snippet demonstrates the request path; it is not a complete OAuth authorization server or a complete internet-facing security configuration.

7. Key flows

The first flow is a tool call. Authentication happens before the MCP handler is created. The query checks membership as part of the read, so a caller cannot gain access merely by guessing a project UUID.

sequenceDiagram
    participant C as "MCP client"
    participant A as "Application Load Balancer"
    participant S as "ECS MCP server"
    participant I as "Cognito token verifier"
    participant D as "RDS PostgreSQL"
    C->>A: POST /mcp with access token
    A->>S: Forward HTTPS request
    S->>I: Verify token claims
    I-->>S: Verified subject
    S->>D: Query issues with membership predicate
    D-->>S: Bounded issue rows
    S-->>C: MCP tool result

Caption: A tool call validates identity before querying user-scoped data.

The second flow illustrates a resource read. The resource URI is a locator, not an authorization credential. The resource handler repeats the membership check and returns no project data when the caller is not a member.

sequenceDiagram
    participant C as "MCP client"
    participant S as "ECS MCP server"
    participant D as "RDS PostgreSQL"
    C->>S: Read project resource URI
    S->>S: Validate token and resource URI
    S->>D: Read overview through membership join
    D-->>S: Overview or no matching row
    S-->>C: Resource contents

Caption: Resource reads use the same identity boundary as tool calls.

Prompts are different: they return a message template and do not require a database read in this example. Treat prompt arguments as untrusted text. A prompt can influence a model, but it must not grant access, choose arbitrary SQL, or bypass a tool’s authorization rules.

8. Build and release

Use Terraform to define infrastructure and a CI pipeline to run tests, build an immutable image, and deploy a specific image digest. Separate infrastructure changes from application releases when the change affects networking, database replacement, or identity configuration.

The following Terraform excerpt shows the core task definition. The ECS service, load balancer, security groups, networking, RDS instance, and Cognito resources are also required; they are omitted here to keep the snippet focused. Inject secrets from Secrets Manager rather than committing database credentials.

resource "aws_ecs_task_definition" "mcp" {
  family                   = "issue-triage-mcp"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = "256"
  memory                   = "512"
  execution_role_arn       = aws_iam_role.ecs_execution.arn
  task_role_arn            = aws_iam_role.mcp_task.arn

  container_definitions = jsonencode([{
    name      = "mcp"
    image     = "${aws_ecr_repository.mcp.repository_url}:${var.image_tag}"
    essential = true
    portMappings = [{
      containerPort = 3000
      protocol      = "tcp"
    }]
    environment = [
      { name = "PORT", value = "3000" },
      { name = "COGNITO_USER_POOL_ID", value = var.user_pool_id },
      { name = "COGNITO_CLIENT_ID", value = var.client_id }
    ]
    secrets = [{
      name      = "DATABASE_URL"
      valueFrom = aws_secretsmanager_secret.database_url.arn
    }]
    healthCheck = {
      command     = ["CMD-SHELL", "node dist/healthcheck.js"]
      interval    = 30
      timeout     = 5
      retries     = 3
      startPeriod = 20
    }
    logConfiguration = {
      logDriver = "awslogs"
      options = {
        awslogs-group         = aws_cloudwatch_log_group.mcp.name
        awslogs-region        = var.aws_region
        awslogs-stream-prefix = "mcp"
      }
    }
  }])
}

The health check should test process readiness and a lightweight dependency condition, not run a full database report. Set database connection limits deliberately: the total maximum connections across tasks must remain below the RDS connection budget.

A small GitHub Actions pipeline can run checks on pull requests and deploy from the protected default branch. Configure GitHub OIDC with a narrowly scoped AWS role; do not store long-lived AWS access keys in repository secrets.

name: mcp-server

on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm run typecheck
      - run: npm test
      - run: npm run test:integration

  deploy:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    needs: test
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: npm
      - run: npm ci
      - run: npm run build
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.AWS_DEPLOY_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}
      - run: ./scripts/build-push-and-deploy.sh

The script should build and push an image tagged with the commit SHA, update the task definition, wait for the service to stabilize, and run a smoke test against the deployed endpoint. A failed smoke test should stop the release and initiate a rollback to the prior task definition.

Test strategy

Test levelWhat to verify
UnitInput limits, result formatting, service behavior, prompt output, and authorization decisions
IntegrationQueries against disposable PostgreSQL; membership boundaries; migrations; connection handling
ContractTool names and schemas, resource URI behavior, prompt arguments, protocol initialization, and error responses
LoadExpected request rate, bounded bursts, database connection use, response latency, and behavior during slow queries

Contract tests should use an MCP client or protocol-level harness rather than only calling handler functions. An implementation can have correct business logic and still expose an unusable protocol contract. Keep a small set of golden contract tests for tool and resource names so an accidental rename is caught before deployment.

9. Observability

Observability is part of the server contract. A failed MCP call should be diagnosable by protocol method, tool or resource name, request ID, and dependency outcome without logging user content or access tokens.

A structured log event can look like this:

{
  "timestamp": "2026-11-02T12:00:00.000Z",
  "level": "info",
  "service": "issue-triage-mcp",
  "request_id": "req-7f4c",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "method": "tools/call",
  "capability": "find-open-issues",
  "outcome": "success",
  "duration_ms": 42,
  "result_count": 8
}

Do not log bearer tokens, raw prompts, full issue descriptions, or database connection strings. If the application needs to correlate a user’s support report with a request, use a carefully governed internal identifier rather than the token subject as a general-purpose log field.

Metrics and tracing

Use RED metrics for the MCP service:

  • Rate: requests by MCP method and capability.
  • Errors: protocol errors, authorization failures, application errors, and dependency timeouts.
  • Duration: request latency, including database time where practical.

Use USE metrics for constrained resources:

  • Utilization: CPU and memory for Fargate; database CPU, storage, and connection use.
  • Saturation: task concurrency, request queueing, database connection pool wait time, and RDS connections near the configured limit.
  • Errors: container restarts, database connection errors, and load balancer target failures.

Instrument Node.js with OpenTelemetry’s Node SDK and auto-instrumentation for HTTP and PostgreSQL. Add spans around MCP operations so traces distinguish protocol handling from database time.

import { NodeSDK } from "@opentelemetry/sdk-node";
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
import { trace } from "@opentelemetry/api";

const sdk = new NodeSDK({
  instrumentations: [getNodeAutoInstrumentations()],
});

await sdk.start();

const tracer = trace.getTracer("issue-triage-mcp");

async function tracedFindIssues<T>(
  projectId: string,
  operation: () => Promise<T>,
): Promise<T> {
  return tracer.startActiveSpan("mcp.find_open_issues", async (span) => {
    span.setAttribute("mcp.capability", "find-open-issues");
    span.setAttribute("project.id", projectId);
    try {
      return await operation();
    } catch (error) {
      span.recordException(error as Error);
      span.setStatus({ code: 2 });
      throw error;
    } finally {
      span.end();
    }
  });
}

Avoid user identifiers and issue content as span attributes. Use low-cardinality attributes such as capability name, transport, and outcome. Configure an exporter appropriate to the deployment and ensure shutdown flushes telemetry during process termination.

SLIInitial SLOMeasurement
Successful MCP requests99.5% over a rolling 30 days, excluding caller validation errorsSuccessful requests divided by eligible requests
Tool latency95% under 1 second for database-backed readsServer-side request duration
Service availability99.5% over a rolling 30 daysSynthetic initialize and read checks
Data recoveryRestore to a point within the configured backup windowRecorded restore exercise

The SLOs are initial operating targets, not guarantees from AWS. Review them after collecting a month of traffic and confirming the client’s retry behavior.

Build one dashboard with request rate, error rate, p50/p95 latency, tool calls by capability, task CPU and memory, desired versus running tasks, target health, database connections, database CPU, and storage. Add a drill-down from request traces to database spans. Page on sustained user-visible failures or imminent saturation; send low-risk trends to a ticket or daily review.

Page-worthy alerts include sustained request failures, an unhealthy or unavailable load-balancer target, repeated task restarts, database connection exhaustion, and database storage approaching its configured limit. A single token rejection or isolated slow request is not a paging event.

10. Security and compliance

An MCP server is an API that can be called by software with model-mediated inputs. Treat every tool argument, resource URI, prompt argument, and returned record as security-relevant.

  • Authentication: Use OAuth access tokens for the remote HTTP service. Publish the protected-resource and authorization metadata expected by supported MCP clients; use the official MCP authorization guidance when implementing discovery.
  • Token validation: Verify issuer, token use, signature, expiry, and intended client. Reject tokens not intended for this service. Do not accept tokens from an arbitrary issuer.
  • Authorization: Derive identity from validated claims, map it to an application user, and enforce membership in every query. Never accept a caller-supplied user ID as authority.
  • Least privilege: Give the ECS task a narrow role for the secret it needs and logs it writes. Give the application database role read-only access to the application tables required for this first server.
  • Input limits: Bound strings, result counts, request body size, and database query duration. Use parameterized SQL.
  • Network: Allow inbound application traffic only from the load balancer. Keep the database private and allow PostgreSQL traffic only from the application security group.
  • Data handling: Return only fields needed by the client. Do not put secrets, personal data, or confidential records into prompt text unless the caller is authorized to receive them.
  • Supply chain: Pin dependency versions through a lockfile, scan dependencies and images, and deploy images by immutable digest.
  • Compliance: Define retention, deletion, and audit expectations before adding sensitive data. This small design does not, by itself, establish compliance with any regulatory framework.

For protocol-specific requirements and current SDK guidance, use the MCP authorization specification and TypeScript SDK documentation.

11. Cost

The following is an assumption-based monthly estimate, not a quote or a statement of current regional pricing. It assumes one region, modest traffic, one small always-on task, a small RDS PostgreSQL instance with limited storage, no NAT Gateway, and no paid support plan. Public pricing changes and regional differences can materially alter the total.

ComponentMonthly estimate assumption
Fargate task, approximately 0.25 vCPU and 0.5 GB, always on$15–$30
Application Load Balancer and light traffic$20–$40
RDS PostgreSQL small instance and 10 GB storage$25–$60
CloudWatch logs, metrics, and traces at low volume$5–$20
Secrets Manager, ECR storage, and small data transfer$5–$15
Cognito usage at small scale$0–$15
Planning total$70–$180/month

The estimate excludes engineering time, taxes, unusually high log volume, backups beyond the assumed retention, and data transfer outside the region. It also assumes a network design without a NAT Gateway; adding one can materially increase the fixed cost. Validate the actual design with the provider’s pricing calculator before committing to a budget.

The cheapest optimization is to avoid unnecessary infrastructure: no Kubernetes cluster, cache, queue, or analytics warehouse until measured workload or product requirements justify one. Do not save a few dollars by disabling backups or weakening access controls.

12. Failure modes, resilience, and disaster recovery

FailureUser-visible effectResponse
Invalid or expired tokenRequest rejectedReturn an authentication error; client obtains a valid token
User has no project membershipEmpty or denied readReturn no protected data; record a low-cardinality authorization outcome
Database unavailableTool and resource reads failUse bounded connection and query timeouts; return a retryable server error
Slow query or connection pool saturationElevated latency and failuresBound query results, inspect plans, cap pool size, and alert on saturation
Fargate task replacementShort interruption if no healthy task remainsHealth checks, deployment health thresholds, and a second task if availability warrants it
Bad application releaseProtocol or handler errorsRoll back to the previous task definition and image
Regional outageService unavailableRestore in another region only if the business accepts the added cost and operational work
Corrupt or deleted dataMissing or incorrect resultsUse managed backups and rehearse point-in-time restore

A single task is the lowest-cost starting point but creates a deployment and host-replacement interruption risk. If uninterrupted service matters, run at least two tasks across availability zones and configure the service’s deployment health settings accordingly. That decision changes the cost estimate and should be driven by the availability SLO.

Enable RDS automated backups with a retention period agreed by the data owner. Document who can restore, where a restore is performed, how the application is pointed at the restored instance, and how integrity is checked. A backup policy that has never been restored is an untested assumption, not a recovery plan.

For the initial single-region system, disaster recovery is restore-based: recreate infrastructure from Terraform, restore the database, reconfigure secrets and identity integration, and verify the MCP contract with smoke tests. Set recovery time and recovery point objectives as explicit business assumptions before claiming a recovery capability.

13. Evolving to the next scale

Do not scale by prediction alone. Use observable symptoms and a specific reason for each new component.

TriggerChangeWhy
Slow queries or rising database CPUImprove indexes and query plans; then resize RDSDatabase tuning is simpler than adding a cache prematurely
Connection saturation after adding tasksReduce per-task pool size or add a managed poolerHorizontal app scaling multiplies connections
Deployment interruptions breach SLORun at least two tasks across availability zonesMaintains a healthy target during replacement
Tool execution becomes long-runningAdd a queue and worker for the affected operationKeeps synchronous MCP requests within a predictable time budget
Multiple teams need independent ownershipSplit service boundaries only where contracts and release cycles differAvoids turning one small service into a distributed system by default
Large or frequently changing resource contentAdd versioning, caching, or a dedicated content storeImproves freshness and database load control
More complex data permissionsIntroduce explicit policy tests and potentially database row-level securityMakes authorization behavior harder to bypass accidentally
Multi-region availability is a real requirementDesign replication, identity, routing, and failover togetherA second region without tested data and routing behavior is not resilience

If a future tool changes external state—creating an issue, sending a message, or changing access—treat it as a separate security design. Add confirmation semantics, idempotency, audit events, narrowly scoped authorization, and explicit failure handling. A read-only tool and a write-capable tool should not quietly share the same privilege model.

14. Phased implementation plan

  1. Define the protocol contract. Name the first tool, resource URI, and prompt. Specify input bounds, response fields, expected errors, and the user’s authorization boundary.
  2. Build locally with stdio. Implement one tool and one prompt, then add the resource. Test with a compatible MCP client and keep stdout reserved for protocol traffic.
  3. Add persistence and authorization. Create the PostgreSQL schema and membership-scoped repository methods. Add tests proving one user cannot read another user’s project.
  4. Add remote transport and identity. Configure Streamable HTTP, OAuth discovery and token validation, request limits, and TLS. Test initialization and capability calls with an MCP client.
  5. Automate quality checks. Add unit, integration, contract, and load tests. Run database migrations in a controlled release step, not automatically from every application task.
  6. Deploy to one region. Provision the load balancer, Fargate service, RDS, secrets, identity integration, and logs using Terraform. Start with conservative capacity and verify real resource use.
  7. Operate deliberately. Add the dashboard, SLOs, alerts, backup policy, and restore runbook. Review traces and capacity after real client traffic arrives.

A first MCP server is successful when its capabilities are understandable, its authorization rules are enforceable, and its operators can explain what happened during a failed request. Start with that small contract. Add sophistication only when the workload, users, or risk profile gives you a concrete reason.


This article was generated with AI. #AIGenerated