Put an enforceable security boundary between autonomous clients and sensitive tools
Remote MCP access creates a boundary where an AI client can request actions that read data, modify systems, or trigger operational workflows. A policy gateway can authenticate clients, restrict tools, validate arguments, request independent approval, enforce limits, and record decisions before a request reaches an MCP server. This guide develops that architecture from the MCP protocol lifecycle upward, explains the controls required for safe enforcement, and provides an adversarial verification plan. It also documents the current bundled McpNet Gateway workflow in Localtonet while keeping connectivity, McpNet access controls, and advanced policy enforcement clearly separated.
📋 What's in this guide
Start with the MCP threat and trust model
An MCP policy gateway is an application-aware enforcement layer between MCP clients and one or more MCP servers. Instead of allowing a connected client to call every tool exposed by a server, the gateway evaluates relevant requests against explicit policy. Depending on its implementation, it may permit a request, deny it, require independent approval, apply narrowly defined transformations, or stop processing because a required security dependency is unavailable.
Network reachability and permission to perform an action are different decisions. A firewall, reverse proxy, or tunnel can determine whether traffic may reach an endpoint. It normally cannot decide whether a particular principal may invoke a specific tool with specific arguments against a specific production resource. That second question belongs at an application-aware boundary that understands MCP messages and the downstream effect of the requested operation.
Document every participant before selecting controls. A client may be a desktop assistant, coding environment, automated agent, orchestration service, or another approved application. MCP servers expose capabilities such as tools, resources, and prompts. Behind those servers are systems of record, including repositories, ticketing services, databases, file stores, build systems, and administrative APIs. The gateway sits on the path and evaluates the trusted context required for each decision.
Classify tools by effect, not by description
A useful inventory records more than a tool name. For every tool, identify whether it reads information, changes reversible state, changes difficult-to-recover state, accesses secrets, affects production, communicates externally, or delegates to another privileged system. Record the argument fields that control scope, such as repository, branch, path, database, environment, account, destination, query, or command.
A label such as “read-only” should be verified against actual behavior. A query tool might still permit expensive operations or access restricted records. A file-reading tool can expose credentials if its path is unconstrained. A deployment tool may have a low-risk preview mode and a high-impact apply mode under the same tool name. Authorization therefore needs to consider arguments and context rather than relying only on a friendly tool description.
Define trust boundaries before selecting a topology
Separate systems when they have different owners, data classifications, credential sets, availability requirements, or incident procedures. A development source-control server and a production database should not automatically share one broad authorization domain merely because both speak MCP. Two teams should not be forced into a common policy lifecycle when neither team is authorized to approve access to the other team’s systems.
Publishing an endpoint through a tunnel solves connectivity. It does not by itself establish per-client identity, semantic argument policy, human approval, rate limits, or a mandatory application audit pipeline. Implement required controls in a gateway or server layer that can reliably inspect and govern the MCP operation.
Design around the MCP protocol, transports, and lifecycle
A policy gateway cannot safely inspect selected JSON fields while ignoring the surrounding protocol. MCP uses JSON-RPC messages, but transport behavior, initialization, capability negotiation, session state, notifications, cancellation, and changing tool catalogs all affect where policy can be enforced. The current architecture should be checked against the official MCP specification and the version negotiated by the client and server.
stdio and Streamable HTTP create different boundaries
With stdio, an MCP client usually launches an MCP server as a subprocess and exchanges protocol messages through standard input and standard output. The operating-system process boundary, executable configuration, local user permissions, environment variables, and inherited credentials become part of the security model. A network tunnel cannot directly publish a stdio stream. A gateway that exposes a stdio server remotely must act as an MCP client toward that subprocess and as an MCP server toward the remote client.
With Streamable HTTP, a remote MCP server exposes an HTTP endpoint. Clients send MCP messages using HTTP POST, while HTTP GET may be used to open a server-to-client stream when supported. Responses can be ordinary JSON or a stream, depending on the request and negotiated behavior. Implementations must also account for HTTP authentication, cross-origin requests, redirects, proxy behavior, connection interruption, and session identifiers. The official MCP transport specification defines the required transport behavior.
| Property | stdio | Streamable HTTP |
|---|---|---|
| Connection boundary | Local process input and output | HTTP endpoint reachable over a network path |
| Typical server lifecycle | Client launches and supervises a subprocess | Server runs independently and accepts multiple remote connections |
| Remote authentication | Usually outside the transport because the process is local | Must be designed for the HTTP resource and its clients |
| Gateway behavior | Gateway becomes the client of the local subprocess | Gateway may terminate and create a separate upstream HTTP session |
| Primary exposure risks | Executable trust, local permissions, environment leakage, subprocess escape | Token misuse, session confusion, SSRF, Origin abuse, direct backend bypass |
Choose session termination or transparent proxying explicitly
A policy-aware gateway will usually need to terminate and re-origin MCP sessions. It behaves as an MCP server toward the downstream client, then creates and maintains its own MCP client session toward each upstream server. This provides a clear place to authenticate the external client, filter capabilities, enforce policy, map request identifiers, manage upstream credentials, and bound messages.
Session termination also creates responsibility. The gateway must correctly handle two lifecycle state machines, possibly with different protocol versions and capabilities. It must not copy a downstream session identifier into an upstream trust context or imply that the upstream authenticated the original user. Request identifiers may need correlation without assuming that both sides use the same identifier space.
A transparent byte-forwarding proxy has less protocol responsibility, but it cannot reliably perform semantic tool authorization if messages are encrypted beyond it, split across streams, or managed through session state it does not understand. If the design claims to enforce tool-level policy, document exactly where MCP is terminated and which component has access to authenticated identity, negotiated capabilities, complete requests, and upstream results.
Respect initialization and capability negotiation
MCP sessions begin with an initialization exchange. The client sends an initialize request that includes its supported protocol version, capabilities, and client information. The server responds with its chosen version, server capabilities, and server information. The client then sends an initialized notification before normal operation proceeds. The official MCP lifecycle specification describes this sequence.
A terminating gateway should negotiate honestly on both sides. It must not advertise a capability to the client unless it can implement or safely relay that capability. It should reject unsupported protocol versions rather than guessing. It should also prevent normal tool operations before initialization completes. If the gateway filters tools, its advertised behavior and discovery responses should reflect the filtered view rather than revealing inaccessible capabilities and denying them only at execution time.
Maintain session identifiers as scoped state
A Streamable HTTP server may assign a session identifier during initialization. The client then sends that identifier on applicable subsequent requests. Treat it as scoped protocol state, not as proof of user identity. Bind it to the authenticated principal and the gateway’s internal session record, reject unknown or malformed identifiers, and prevent one principal from replaying another principal’s session.
A terminating gateway should maintain a separate upstream session identifier. Never assume that a downstream identifier can be forwarded unchanged or used to authorize an upstream request. Define expiration, cleanup, reconnect, and revocation behavior. If the implementation supports session termination through HTTP DELETE, ensure that termination affects only the authenticated caller’s intended session.
Handle notifications, cancellation, and catalog changes
MCP notifications do not have response identifiers, but they can still change security-relevant state. Validate their direction and lifecycle state before forwarding them. Do not allow an unexpected notification to mutate another principal’s session or trigger uncontrolled work.
Cancellation requires particular care. A cancellation notification refers to an in-flight request, so the gateway needs a bounded mapping between downstream and upstream request identifiers. It should forward cancellation only to the matching operation. Cancellation is not a transaction rollback guarantee. A downstream tool may already have produced a side effect, so the audit result should distinguish “cancellation requested” from “operation reversed.”
Tool catalogs can change during a session. When an upstream server supports tool-list change notifications, the gateway should refresh its inventory, recompute the client-visible filtered list, and notify the client only when appropriate. A newly discovered tool must remain denied until policy explicitly grants it. Removed or materially changed tools should invalidate stale assumptions, schemas, and pending approvals.
Bound requests, streams, and responses
Enforce limits before expensive parsing and throughout response handling. Relevant limits include HTTP body size, JSON nesting depth, field count, string length, concurrent requests, open streams, event size, cumulative stream bytes, tool result size, and execution duration. A server-controlled stream must not be able to hold unlimited gateway memory or connections.
Treat upstream results as untrusted input. Tool output may contain secrets, malicious instructions, malformed content, huge payloads, or links to attacker-controlled resources. Policy enforcement does not make returned text safe for a model. Apply result-size limits, content classification, redaction, and downstream timeouts according to the protected environment.
Apply the MCP HTTP authorization security model
For protected HTTP transports, follow the official MCP authorization specification and MCP security guidance. OAuth-based authorization for HTTP deployments must be implemented as a complete trust flow rather than reduced to “a bearer token exists.”
The MCP server or terminating gateway is the protected resource. It should validate token signature and validity, expected issuer, intended audience or resource, scopes, and other applicable constraints. A token issued for another service must not be accepted merely because it is structurally valid. Audience validation helps prevent a token intended for one resource from being replayed against another.
Do not pass the client’s access token through to an upstream MCP server or unrelated API. Token passthrough collapses trust boundaries, can expose credentials to services that were never intended to receive them, and makes audience and least-privilege enforcement ineffective. The gateway should authenticate the client token for its own resource, make an authorization decision, and use a separate upstream credential intended for the upstream resource.
Confused-deputy defenses are essential when the gateway can act with stronger authority than the caller. Bind authorization to the exact resource, client, redirect context, and requested operation. Do not let arbitrary caller-controlled URLs choose authorization endpoints, token endpoints, upstream MCP servers, or credential destinations.
Protect outbound requests against server-side request forgery. Resolve upstream destinations from controlled configuration, restrict schemes and ports, block loopback, link-local, private, metadata, and other prohibited address ranges where they are not explicitly required, and revalidate redirect destinations. Account for DNS changes and alternate IP representations rather than validating only the original hostname text.
Streamable HTTP servers should validate the HTTP Origin header where applicable. This helps prevent malicious websites from using a victim’s browser to reach a locally bound MCP service through DNS rebinding or cross-origin requests. Local servers should bind only to intended interfaces, require authentication where remote access is possible, and avoid trusting a hostname merely because it initially resolved to a safe address.
Controls a policy gateway should enforce
A strong design uses independent controls. Authentication establishes who or what is making the request. Authorization decides whether that identity may invoke the capability. Validation constrains how an allowed capability may be used. Approval introduces a separate decision maker for selected actions. Rate limiting bounds frequency and resource use. Audit events preserve evidence. Credential isolation limits what can be stolen or misused if a client or model session is compromised.
Establish identity before evaluating policy
Do not authorize requests using a client name, model-generated field, unverified header, or MCP session identifier. Identity must come from a mechanism trusted by the deployment. Normalize the result into a stable internal principal while retaining appropriate authentication context for investigation. If a human delegates work to an agent, record both the initiating user and executing workload when the identity system supports that distinction.
Use default-deny tool allowlists
Reject tools unless policy explicitly grants access. Grants should name the canonical server, tool, permitted principal or group, environment, and relevant conditions. Avoid broad wildcards because a server can add a new administrative tool after the original review. If names or aliases cannot be normalized unambiguously, deny the operation.
Validate arguments semantically
Schema validation is necessary but not sufficient. A syntactically valid string may identify a forbidden directory, repository, database, branch, account, host, or environment. Canonicalize paths and identifiers before authorization. Enforce approved roots, enumerated environments, safe numeric ranges, controlled destinations, and permitted modes. Reject unknown fields when they can alter behavior.
Require independent approval for selected actions
High-impact requests may require a decision from an authorized human or independent service. Bind approval to the authenticated principal, canonical server and tool, normalized argument digest, environment, policy version, creation time, expiration time, and approver. Re-evaluate policy before execution. Changed arguments, expired approvals, self-approval, and replay must not authorize the action.
Apply multidimensional rate limits
Useful dimensions include principal, user, tool, server, session, destination, and organization. Expensive or destructive tools need stricter limits than inexpensive reads. Concurrency limits should prevent a client from launching many long-running actions simultaneously. Define fail behavior when the limiter is unavailable rather than silently removing a critical protection.
Create privacy-aware audit events
Record the timestamp, correlation identifier, authenticated principal, target server, canonical operation, decision, reason code, policy version, approval reference, and execution outcome where known. Avoid logging full arguments and responses by default because they can contain credentials, personal data, source code, and confidential operational details. Prefer selective redaction, classified fields, and hashes for exact approval binding.
| Control | Decision question | Safe failure behavior |
|---|---|---|
| Authentication | Can the gateway verify the client or workload? | Reject missing, expired, revoked, or unverifiable identity. |
| Tool authorization | May this principal invoke this canonical tool on this server? | Deny unless an applicable grant exists. |
| Argument policy | Are the structure, values, and requested scope permitted? | Reject malformed, ambiguous, unknown, or out-of-scope input. |
| Approval | Does this exact request have valid independent approval? | Do not execute while approval is absent, expired, or mismatched. |
| Rate limiting | Is the operation within identity, tool, and destination limits? | Reject or defer according to explicit policy. |
| Audit pipeline | Can required decision evidence be retained? | Block critical operations if mandatory evidence cannot be recorded. |
| Downstream access | Is the selected credential limited to the approved action? | Reject rather than substituting a broader credential. |
Reference architecture for policy-aware MCP ingress

A clean architecture separates transport termination, identity verification, MCP lifecycle state, policy decisions, approval state, downstream routing, credential access, and audit delivery. These responsibilities can begin in one deployable service, but their interfaces should remain explicit so the behavior is testable and sensitive functions can later be isolated.
Request processing sequence
Establish the authenticated principal before trusting application metadata. Parse the MCP message with bounded input handling, verify that the session is initialized, identify the operation, resolve the target server and canonical tool, validate arguments, and construct the policy input. If policy denies the operation, return a controlled error without forwarding it.
If approval is required, store a pending request that is bound to the normalized action. Do not hold broad credentials in an unbounded waiting process. After approval arrives through a trusted channel, verify its scope and expiration, then evaluate current policy again.
Only after the final allow decision should the gateway select downstream authorization and route the call. The gateway then correlates the response, applies result limits or redaction obligations, records the outcome, and returns a protocol-compatible response to the client.
The following is an illustrative policy input. It is not an MCP message, McpNet configuration file, or Localtonet format:
{
"principal": {
"id": "workload:build-assistant",
"user": "user:approved-operator",
"groups": ["engineering"]
},
"request": {
"server": "source-control",
"tool": "create_change_request",
"arguments": {
"repository": "approved-project",
"targetBranch": "main"
}
},
"context": {
"environment": "production",
"sessionId": "redacted",
"approvalId": null
}
}
Prevent direct and indirect bypasses
Protected backends should not remain independently reachable by the same untrusted clients. Bind them to private interfaces where appropriate, use host firewall or network policy restrictions, and configure backend authentication so only the gateway or a separately approved administrative path can connect.
Also examine indirect delegation. A permitted tool that accepts an arbitrary command, URL, query, plugin, or nested tool identifier can reproduce denied capabilities. If one broad tool can perform every restricted action, a narrow allowlist provides little practical protection.
Blocklists miss alternate encodings, aliases, path normalization, nested input, redirects, and semantically equivalent operations. Parse expected structures, canonicalize values, allow known-safe scopes, and reject ambiguity.
Isolate credentials from clients and models
A model should not need to see a repository token, database password, cloud credential, or administrative secret to request an approved tool action. Keep downstream credentials in a protected service context and select them only after authorization. Use separate credentials for different trust boundaries and permission levels whenever the downstream system supports that separation.
Choose the right gateway deployment pattern
The appropriate topology depends on tool sensitivity, team boundaries, credential isolation, policy ownership, availability requirements, and operational maturity. Direct exposure, one gateway per trust boundary, a shared gateway, and a hybrid model each have valid uses.
| Pattern | Best fit | Main advantage | Main concern |
|---|---|---|---|
| Direct MCP exposure | Low-risk environments where the server enforces every required control | Fewer components | No independent policy boundary |
| Gateway per trust boundary | Systems with distinct owners, credentials, or risk levels | Strong isolation and smaller failure impact | More deployments and policy lifecycles |
| Shared gateway | Organizations requiring consistent identity and policy integration | Central governance | Larger blast radius if isolation is weak |
| Hybrid model | Central standards with separately protected sensitive environments | Shared conventions with runtime isolation | Ownership and policy boundaries must remain clear |
Direct exposure can be reasonable when the MCP server itself provides robust authentication, granular authorization, validation, auditing, and narrowly scoped tools. It can also fit a disposable local test environment with no sensitive data or credentials. It becomes unsuitable when clients require different permissions, high-impact actions need independent approval, or one server aggregates multiple credential domains.
A gateway per trust boundary limits credential mixing and lets production follow stricter rules than development. The tradeoff is duplicated monitoring, updates, policy distribution, and incident work. A shared gateway reduces that duplication but becomes a high-value service. It requires internal tenant isolation, explicit routing, per-boundary credentials, capacity controls, and divided policy administration.
Implementation workflow for a policy gateway
“MCP policy gateway” describes an architectural role, not one universal package. Exact commands, configuration files, transports, and authentication integrations depend on the selected implementation. The sequence below is an engineering workflow rather than a claim about built-in McpNet Gateway features.
Inventory servers, tools, effects, and owners
Record capabilities, backend systems, credential requirements, data classifications, expected clients, side effects, and arguments that determine scope. Remove tools that should never be remotely callable.
Choose transports and termination boundaries
Document whether each upstream uses stdio or Streamable HTTP, where MCP sessions terminate, how initialization is negotiated, and how downstream and upstream session state remain separate.
Define identities and trust boundaries
Select trusted client authentication, stable principal identifiers, token audiences, and separate boundaries for different owners, credentials, environments, or risk levels.
Write default-deny authorization rules
Grant named principals access to named servers and tools. Add conditions for environments, repositories, paths, accounts, and other resource boundaries. Keep newly discovered tools denied.
Implement bounded protocol handling
Enforce initialization order, capability compatibility, session ownership, request mapping, cancellation, notification direction, message limits, stream limits, timeouts, and bounded results.
Add semantic policy and supporting controls
Canonicalize arguments, enforce approved scopes, bind approvals to exact actions, apply multidimensional limits, and emit privacy-aware decision evidence.
Isolate backends and credentials
Prevent direct backend access, prohibit token passthrough, restrict outbound destinations, and select only the downstream credential needed for the allowed operation.
Test locally before adding public connectivity
Verify allowed, denied, malformed, cancelled, approval-required, rate-limited, revoked, catalog-change, and dependency-failure cases against safe fixtures. Expose only the reviewed gateway after these controls pass.
McpNet Gateway documents an admin token, client bearer tokens, and client scoping through AllowedServerIds and AllowedGroupIds. Those controls are useful, but they are not evidence that McpNet Gateway implements every control in this architecture. Independent human approval, semantic argument policy, custom rate-limit dimensions, result transformation, mandatory audit delivery, and every OAuth security control must be verified in the actual component selected to provide them.
Verify controls with adversarial scenarios
A successful request proves only that one path works. Security testing must demonstrate that forbidden and malformed requests fail safely, backend services receive nothing after a denial, and operational evidence accurately describes the outcome. Run tests locally first, then repeat them through the remote endpoint.
Protocol and session tests
Attempt tool calls before initialization, send an unsupported protocol version, advertise incompatible capabilities, omit a required session identifier, replay another principal’s identifier, and send notifications in an invalid lifecycle state. Verify that the gateway rejects these cases without creating upstream side effects. Interrupt streams and confirm that memory, connections, and session records are released within defined bounds.
Allowed, denied, and newly discovered tools
Use a principal with one narrow permission and invoke a safe fixture tool with approved arguments. Confirm one matching backend invocation. Then request a real but unauthorized tool and verify explicit denial with no backend call. Add a new backend tool without changing policy. It should remain unavailable even if a tool-list change notification refreshes discovery.
Malformed and out-of-scope arguments
Test missing fields, unexpected fields, wrong types, oversized values, excessive nesting, invalid enumerations, duplicate identifiers, encoded paths, redirects, and alternate address formats. Then test valid structures containing forbidden repositories, production environments, parent-directory paths, broad queries, or unapproved network destinations.
Approval integrity
Submit a high-impact fixture and confirm that the backend is not called while approval is pending. Approve the exact action using an authorized identity. Then modify one argument, switch tools, reuse the approval, attempt self-approval, and retry after expiration. Each variation should fail.
Token and authorization tests
Try missing, expired, revoked, malformed, incorrectly signed, wrong-issuer, and wrong-audience tokens. Confirm that a token issued for another resource is rejected. Verify that the incoming token never appears in upstream authorization headers, logs, errors, or tool arguments. Test authorization redirects and resource metadata against confused-deputy and open-redirect conditions if the deployment uses OAuth.
SSRF, Origin, and DNS rebinding tests
Attempt to route an upstream connection to loopback, link-local, cloud metadata, private infrastructure, unexpected ports, alternate IP encodings, and redirect chains. Verify the configured policy. Send absent and hostile Origin values where browser-origin traffic is relevant. Test DNS changes between validation and connection so destination controls do not rely on a one-time hostname check.
Cancellation and bounded-response tests
Cancel an in-flight request and confirm that the gateway maps cancellation only to that operation. Verify that it does not falsely report rollback if the backend already changed state. Return oversized JSON, long-running streams, rapid events, deeply nested results, and slow responses from a fixture server. The gateway should enforce limits without exhausting shared capacity.
Dependency and bypass tests
Make identity, policy, approval, rate-limit, credential, and required audit dependencies unavailable one at a time. Verify documented failure behavior and bounded retries. Attempt direct connections to every protected backend using alternate addresses, legacy listeners, development ports, and container-published ports. Those routes should fail or require a separately approved administrative identity.
| Scenario | Expected gateway result | Backend evidence |
|---|---|---|
| Allowed tool and scope | Allow under the expected policy version | One matching invocation |
| Denied or newly added tool | Explicit denial | No invocation |
| Invalid session or lifecycle state | Protocol error without forwarding | No invocation |
| Wrong token audience | Authentication rejection | No invocation and no token passthrough |
| Malformed or out-of-scope arguments | Validation or authorization denial | No invocation |
| Missing or mismatched approval | Pending or denied | No invocation |
| Oversized result or stream | Bounded termination with controlled error | Connection and memory released |
| Direct backend bypass | Connection unavailable or separately protected | No unauthorized invocation |
Operate the gateway as a security control
Tool catalogs, schemas, client identities, backend permissions, and threat conditions change. Operations should detect these changes before they become silent privilege expansion.
Review catalog and schema drift
Compare the current backend inventory with the reviewed inventory. New, removed, or changed tools should trigger review. Description and schema changes matter because they can alter model behavior and argument structure even when the tool name remains the same. Invalidate cached policy assumptions and pending approvals when a material tool definition changes.
Version policy and protocol support
Store policy as controlled configuration with an owner, reviewer, version, test suite, and rollback process. Track supported MCP protocol versions and capabilities in the same operational discipline. An upgrade that changes transport, session, or notification behavior should pass compatibility and negative security tests before release.
Monitor decisions and outcomes
Useful signals include repeated denied tools, validation failures, wrong-audience tokens, approval requests outside normal patterns, high denial rates, attempts to access many servers, unusual execution frequency, catalog drift, session errors, oversized results, and policy dependency failures. Distinguish allowed from completed, allowed from failed, denied, pending, cancelled, expired, and rate-limited.
Prepare incident actions
Define how operators revoke a client token, terminate sessions, disable one tool, isolate one backend, stop remote connectivity, invalidate approvals, rotate downstream credentials, and preserve audit evidence. Confirm that revocation reaches every gateway instance and that queued work does not execute after access is removed.
Tool arguments and results can contain credentials, personal data, proprietary code, and sensitive operational details. Redact or omit unnecessary values, control access to event storage, protect it from alteration, and define retention according to organizational requirements.
Expose McpNet Gateway with Localtonet
Localtonet can expose a locally running McpNet Gateway without inbound router port forwarding, firewall changes, VPN setup, or a public IP address. Our client establishes an outbound connection to a Localtonet relay server, and the MCP Gateway tunnel provides a public HTTPS address. The tunnel is available only while the selected device is connected and the tunnel is running.
There are two deployment paths, and they should not be mixed. The primary path uses McpNet Gateway bundled with the Localtonet client. The optional path runs McpNet Gateway separately from NuGet or its source repository. The bundled path has automatic local behavior and a dedicated four-field tunnel workflow. A standalone installation has its own security configuration and may use a different local port.
Primary path: bundled McpNet Gateway
McpNet Gateway is bundled with the Localtonet client and starts automatically on local port 5050. There is no separate gateway package to install for this path. The bundled configuration does not start in unauthenticated Dev mode. Its admin token is set through Localtonet’s settings rather than through a standalone appsettings.json file.
Before creating a public tunnel, configure the gateway’s client access. Remote MCP clients authenticate with a client bearer token, not the Localtonet device token and not the gateway admin token. Scope each client token using AllowedServerIds and AllowedGroupIds so it can discover and use only the intended upstream servers or groups.
In McpNet Gateway client-token configuration, leaving both AllowedServerIds and AllowedGroupIds empty grants access to all upstream servers. Configure at least one appropriate scope before exposing the endpoint. Use a different client token for callers that require different access.
Keep three credentials distinct: the Localtonet device token identifies the client device that runs the tunnel, the McpNet admin token protects gateway administration, and an McpNet client token authorizes an MCP client. Do not place any of them in source control, screenshots, shared logs, or article examples.
Install the Localtonet client and sign in with the device token
Open the MCP Gateway page, download the current Localtonet client for the supported platform, install it, and sign in using the token associated with that device. McpNet Gateway starts automatically alongside the client on port 5050. Set or change the McpNet admin token in Localtonet’s settings, then create a separate client token and configure its AllowedServerIds or AllowedGroupIds before public exposure.
Complete the four MCP Gateway tunnel fields
On the MCP Gateway creation screen, select Process Type, Auth Token, Server, and Domain. Process Type controls the public hostname option. Auth Token selects the Localtonet device that runs the tunnel. Server selects an option currently available in the dashboard. Domain selects the available Localtonet or previously configured custom-domain option. The bundled workflow does not require a manual local host or port because the dedicated tunnel forwards the bundled gateway’s /mcp and /dashboard routes.
Select Create, then Start
Create saves the tunnel configuration, but it does not mean the tunnel is running. Use the Start control for the newly created tunnel. Confirm that the selected Localtonet device is connected and the tunnel reports as running.
Connect the MCP client to the public /mcp endpoint
Configure the approved MCP client to use the assigned public HTTPS address followed by /mcp. Send the scoped McpNet client token as an Authorization bearer token. Do not use the admin token or Localtonet device token in the MCP client configuration. Verify discovery and a safe tool call before allowing higher-impact operations.
MCP URL: https://your-assigned-domain.example/mcp
Authorization: Bearer YOUR_SCOPED_MCPNET_CLIENT_TOKEN
The hostname above is deliberately a placeholder. Use the exact address assigned to your tunnel. Available process types, domains, servers, and plan-dependent options must be read from the current Localtonet dashboard rather than copied from an old deployment.
Verify the bundled path locally and remotely
First confirm that the Localtonet client is running and the bundled gateway is available locally on port 5050. Use an approved local MCP client or the gateway’s supported local interface to verify authentication, upstream discovery, and a harmless tool call. Confirm that the scoped client sees only the servers or groups intended by its ACL.
After starting the tunnel, repeat discovery and the same harmless operation through the public /mcp URL. Test a token with intentionally narrow access and confirm that excluded upstream servers are unavailable. Also test a missing or invalid client token. Public reachability without valid McpNet client authentication should not grant tool access.
If an upstream server runs through npx, its package may download on first connection. The documented McpNet behavior allows up to 120 seconds per server, and the tool list may populate on the next background refresh about 60 seconds later. A first tool call can therefore time out while the upstream warms up. Wait for that initialization and retry once before treating it as a tunnel failure.
Stop or remove remote connectivity
Use Stop when the public path is temporarily unnecessary. Delete the tunnel when its configuration should no longer exist. Stopping or deleting a Localtonet tunnel removes that connectivity path, but it does not revoke an McpNet client token automatically. Revoke or rotate the client token separately when a caller should no longer have access.
Optional path: standalone McpNet Gateway
A standalone McpNet Gateway installed from NuGet or built from its source repository is a separate deployment. Unlike the bundled configuration, the standalone build starts in Dev mode by default according to the current Localtonet setup guide. Do not expose it in that state. Switch it to Enterprise mode and set a strong admin token using the standalone gateway’s supported configuration:
McpGateway__Mode=Enterprise
McpGateway__AdminToken=your-strong-admin-token
The value shown is a placeholder and must not be reused. Configure scoped client tokens and verify authentication before adding a public route. A standalone gateway can still use Localtonet’s MCP Gateway tunnel type, but it points to the port used by that standalone instance rather than assuming the bundled service on port 5050. Follow the current standalone and Localtonet interface instructions for selecting that instance instead of applying the bundled no-host-or-port workflow blindly.
Standalone deployments also require you to manage process startup, updates, local binding, credentials, logs, and service availability. Verify whether the standalone listener is reachable only from the Localtonet client device, validate Origin handling for HTTP access, and keep upstream MCP servers inaccessible through alternate public routes.
What Localtonet and McpNet do not establish by themselves
Localtonet provides remote connectivity to the selected gateway. McpNet Gateway documents admin authentication, client bearer tokens, and server or group ACL scoping. These facts do not prove that the combined system implements independent human approval, semantic argument validation, custom policy reason codes, multidimensional rate limits, mandatory audit delivery, OAuth audience validation for every identity provider, response redaction, or every other conceptual control described in this article.
If those controls are required, verify them in McpNet Gateway’s current documentation or add a dedicated policy component that can enforce them without breaking MCP initialization, sessions, notifications, cancellation, and tool-list changes. The public tunnel should terminate at the reviewed enforcement path, never at a backend that bypasses it.
For the current product workflow, see our guide to exposing McpNet Gateway with Localtonet. The Localtonet MCP Server for tunnel management is a separate capability that lets supported AI assistants manage Localtonet resources. It is not the McpNet Gateway that aggregates and exposes your own upstream MCP servers.
Frequently asked questions
What is an MCP policy gateway?
An MCP policy gateway is an application-aware enforcement point between clients and MCP servers. It can terminate MCP sessions, establish verified identity, evaluate tools and arguments, route allowed operations, and record decisions. It is an architectural role rather than one universal software package.
Should a policy gateway transparently proxy MCP traffic?
Usually not if it claims to enforce semantic tool policy. A policy-aware gateway normally terminates the client session and creates a separate upstream session so it can validate lifecycle state, identity, capabilities, tool calls, and responses. A transparent transport proxy provides connectivity but has limited ability to enforce application policy.
Can an access token received from an MCP client be forwarded upstream?
No. Token passthrough can disclose credentials to an unintended resource and defeats audience separation. Validate the incoming token for the gateway’s resource, authorize the operation, and use a separate credential intended for the upstream server or protected API.
Does a Localtonet MCP Gateway tunnel provide per-tool authorization?
The tunnel provides connectivity. McpNet Gateway separately documents client bearer tokens and access scoping through AllowedServerIds and AllowedGroupIds. More advanced controls such as semantic argument policy, independent approval, and a mandatory audit pipeline must be verified or implemented in an appropriate application layer.
What happens if AllowedServerIds and AllowedGroupIds are both empty?
The documented McpNet behavior grants that client token access to all upstream servers. Configure one or both ACL fields before exposure unless full access is an intentional and reviewed requirement.
Why can the first remote tool call time out?
An upstream launched through npx may need to download its package on first connection. McpNet allows up to 120 seconds per server, and tool discovery may update on the next background refresh about 60 seconds later. Retry once after warm-up before diagnosing the tunnel itself.
Why is a tool allowlist not sufficient?
A permitted tool can still target an unauthorized repository, path, database, account, environment, or network destination. Some tools also expose both safe and destructive modes. Combine canonical tool authorization with semantic argument validation, least-privileged credentials, limits, and approval where required.
When is the Localtonet public endpoint available?
The endpoint is available only while the selected Localtonet device is connected and the tunnel is running. Creating the tunnel does not start it. Use Start after creation, and stop or delete the tunnel when remote connectivity is no longer required.
Connect your reviewed MCP gateway with Localtonet
Configure scoped McpNet client access, verify the gateway locally, then use the dedicated Localtonet MCP Gateway tunnel to provide the approved public HTTPS connection without inbound router port forwarding.
Get Started Free →