27 min read

Safe Tunnel Automation for CI Pipelines and AI Agents

Design secure Localtonet tunnel lifecycles with explicit state control, protected tokens, webhook verification, idempotency, and reliable cleanup.

CI and AI automation controlling a tunnel through explicit states, protected credentials, verified webhooks, and cleanup.
Safe tunnel automation separates control, observed state, credentials, and cleanup.
Developer Tools · Tunnel Automation · Localtonet · 2026

Build predictable tunnel lifecycles for pipelines, development environments, and coding agents

Automated tunnel management is not simply a matter of creating a tunnel and assuming it is reachable. A reliable workflow must protect device-specific authentication tokens, select a currently available relay, start the tunnel explicitly, verify its observed state, and clean it up when the job ends. In this guide, we design that lifecycle for CI pipelines and AI coding agents using the Localtonet REST API, the Localtonet MCP Server, or controlled dashboard operations. Exact API routes, payloads, server codes, and plan availability can change, so we deliberately separate durable architecture from values that automation must obtain from current Localtonet documentation or the dashboard.

🔒 Device-specific token boundaries 🌐 Explicit create, start, verify, stop, and delete states ⚡ CI and AI-agent cleanup patterns

The correct mental model for tunnel automation

Localtonet exposes a service running on a machine or reachable from that machine through an outbound connection to a Localtonet relay server. This avoids requiring inbound router port forwarding, firewall changes, VPN setup, or a public IP address. Depending on the tunnel family, the result is a public URL or a public host and port.

The outbound connection is important to automation architecture. A control-plane operation can create a tunnel configuration, but that configuration still depends on a selected client device being connected and able to reach the local target. The tunnel is available only while that device is connected and the tunnel is running.

This gives us several separate facts that should never be collapsed into one boolean called “deployed”:

🧾 Configuration exists A tunnel record has been created with a tunnel family, target information, device token, and relay selection. Creation alone does not mean the tunnel is running.
💻 Device is connected The selected Localtonet client must be online. A valid configuration cannot serve traffic through a disconnected client.
▶️ Tunnel is started Starting is an explicit lifecycle action. A tunnel should not be treated as active merely because its configuration was created successfully.
🔌 Target is reachable The application must be listening on the configured local IP address and port, or the selected target must otherwise be valid for that tunnel family.
✅ Public path is verified A consumer should test the assigned public URL or host and port instead of inferring availability from a successful create or start request.
🧹 Ownership is recorded Automation needs enough durable state to stop or delete only the resource that belongs to the current workflow.

A safe controller therefore maintains both desired state and observed state. Desired state expresses what the pipeline or agent wants, such as “this HTTP tunnel should be running for the duration of integration tests.” Observed state expresses what the system can confirm, such as “the device is connected,” “the tunnel reported Connected,” and “the public health check succeeded.”

Creation is not availability

Localtonet tunnel creation and tunnel startup are distinct operations. Your automation must issue the supported start action and then verify availability. Do not mark a deployment successful after creation alone.

Choose the right control interface

Localtonet can be managed from a single dashboard or REST API. We also provide the Localtonet MCP Server, which lets compatible AI coding assistants such as Claude Code and Cursor create, start, and stop Localtonet tunnels directly from the assistant. These interfaces solve related problems, but they should not automatically receive the same authority.

Interface Best fit Control characteristics Primary safety concern
Localtonet REST API Deterministic CI jobs, platform controllers, scheduled automation, and repeatable environment management Suitable for explicit program logic, persisted identifiers, retries, reconciliation, and machine-readable results Protect API credentials and use only current documented routes, fields, and values
Localtonet MCP Server Interactive coding sessions in which an assistant needs to create, start, or stop a tunnel Allows supported tunnel actions to be requested from an AI coding assistant Constrain tool permissions and require human approval for sensitive or destructive actions
Localtonet dashboard Manual setup, one-off work, review, recovery, and low-frequency administration Human-visible configuration and explicit Start, Stop, and Delete controls Avoid undocumented manual changes to resources owned by active automation

Use the REST API for deterministic controllers

Direct API automation is normally the best architectural fit when a pipeline must perform the same lifecycle on every run. The controller can validate inputs, record the returned tunnel identifier, start the tunnel, wait for confirmation, run tests, and execute cleanup in a finalization stage.

This article does not provide guessed REST endpoints, request bodies, authentication headers, or response properties. Those details must come from current Localtonet API documentation when the implementation is built. The same rule applies to relay server codes and plan-dependent availability. Hardcoding an undocumented value creates brittle automation and can accidentally direct traffic somewhere other than intended.

Use the MCP Server for supervised assistant workflows

The Localtonet MCP Server is useful when a developer asks an assistant to expose a local application while debugging, reviewing a user interface, or testing an external integration. The supported scope established here is creating, starting, and stopping tunnels. We do not assume additional MCP operations that have not been confirmed.

An AI agent should be treated as an operator acting through tools, not as an infallible control plane. A natural-language instruction can be ambiguous, stale context can point to the wrong process, and a retry can repeat a side effect. Tool approval, resource scoping, confirmation before exposure, and a cleanup deadline are therefore important even during interactive development.

Keep the dashboard available for review and recovery

Manual dashboard management remains appropriate for learning the workflow, reviewing current state, handling an exceptional failure, or managing a small number of long-lived tunnels. It is also useful as an operational recovery interface when a CI runner fails after creating a resource but before deleting it.

Teams should nevertheless decide who owns each tunnel. If automation owns a resource, manual operators should avoid modifying or deleting it while the controller is active. If a human takes ownership during an incident, pause the relevant controller first so that it does not immediately recreate or alter the resource.

Design an explicit Localtonet tunnel lifecycle

Tunnel lifecycle state machine with creation, activation, failure handling, retries, reconciliation, and deletion.
Explicit states and guarded transitions make tunnel creation and cleanup repeatable.

A production-quality workflow should model each transition rather than issuing loosely related commands. The durable sequence below follows the documented Localtonet workflow at the level supported by our current product context. Exact API mechanics are intentionally left to current API documentation.

1

Install and run the Localtonet client

Run the Localtonet client on the device that hosts the target service or can reach it over the local network. Confirm separately that the application itself is listening and healthy before creating public exposure.

2

Authenticate or select the intended device

Use the device-specific authentication token associated with the client that should run the tunnel. Obtain the token through an authorized Localtonet workflow, keep it secret, and never copy a token from examples or logs.

3

Select a currently available relay

Choose the relay server or region from current Localtonet product data. Do not embed a guessed server code in source code or an AI prompt. Availability can vary, so treat relay selection as validated configuration.

4

Create the appropriate tunnel configuration

Select the tunnel family that matches the target. HTTP, TCP, UDP, combined UDP/TCP, and TLS tunnels use a local IP address and port. File Server uses a local folder path. Proxy tunnel types make the connected device the proxy exit node and do not use a conventional local IP and port target.

5

Start and verify the tunnel

Issue the explicit Start operation after creation. Record the assigned public URL or public host and port, wait for relevant state confirmation, and perform an application-level check through the public address before allowing dependent work to proceed.

6

Stop or delete the tunnel during cleanup

Stop the tunnel when exposure is no longer needed. Delete an ephemeral tunnel when the workflow owns it and retention is unnecessary. Cleanup should run after success, failure, cancellation, and timeout.

Define meaningful internal states

Your implementation can use its own internal state names without assuming that they are literal Localtonet API values. A useful controller model might distinguish requested, configured, start-requested, observed-connected, application-ready, stop-requested, observed-disconnected, and deleted. These are design concepts for your automation, not a claim about exact API response strings.

Keep configuration readiness and application readiness separate. A Connected event can confirm a platform-level transition, but the target application might still be starting, bound to the wrong interface, returning an error, or waiting for a dependency. Only an application-aware probe can establish that the public route serves the behavior needed by the test.

Choose the correct tunnel family

Tunnel family Target supplied to Localtonet Typical automation consideration
HTTP/s Local IP address and port Useful for web applications and HTTP callbacks; verify with an application-level HTTP request
TCP or TLS Local IP address and port Verify that the expected service accepts a connection and, where appropriate, completes its protocol handshake
UDP Local IP address and port A simple connection test is insufficient because UDP is connectionless; use a protocol-aware request and response
Combined UDP/TCP Local IP address and port Test both required transports rather than assuming one successful path proves the other
File Server Local folder path Scope the published folder carefully and avoid exposing unrelated files or credentials
HTTP or SOCKS5 proxy The connected device acts as the exit node Do not model this as forwarding to an ordinary local application target
Do not publish a broader target than the workflow needs

Confirm the local service, interface, port, or folder before starting the tunnel. Protect the exposed application with appropriate authentication and least-privilege access controls. A tunnel provides connectivity, but it does not remove the need for application authorization or responsible network policy.

Protect device tokens and automation credentials

A Localtonet authentication token identifies the client device that will run a tunnel. Tokens are device-specific and must not be guessed, exposed, committed to a repository, embedded in an image, pasted into an issue, or placed in an AI conversation. Treat the token as a secret throughout its lifecycle.

Use the CI secret store

Supply required credentials through the CI platform’s protected secret mechanism rather than a tracked configuration file. Restrict who can edit the pipeline, who can read or use protected variables, and which branches or environments may access them. Avoid passing secrets as ordinary command arguments when the selected official integration supports a safer mechanism, since command lines may appear in process listings or logs.

Redaction is a backup control, not the primary defense. A masking system might fail if a value is transformed, split, encoded, included inside structured output, or returned by an overly verbose diagnostic command. Configure the job so that secret values are never printed in the first place.

Separate credentials by environment and device

Development, testing, and production should not all depend on one broadly shared device identity. Device-specific separation reduces the effect of accidental exposure and makes ownership clearer. A pipeline intended to expose an isolated test service should not receive credentials for an unrelated developer workstation or production host.

Apply the same separation to AI assistants. A local coding assistant should receive only the tools and credentials needed for the current workspace. Do not place a long-lived token in repository instructions, generated code, shell history, model context, or an assistant memory feature.

Prevent indirect disclosure

Review artifacts as carefully as console logs. Build traces, environment snapshots, test reports, crash dumps, copied configuration directories, and debugging bundles can all retain sensitive values. If an incident suggests that a token was exposed, stop relying on it and follow the current Localtonet process for replacing the affected credential. This article does not invent a rotation endpoint or dashboard sequence.

Never place a real token in sample code

Use a secret reference in pipeline configuration and sanitized placeholders in documentation. If an AI agent needs Localtonet access, expose the minimum approved tool capability rather than pasting credentials into the prompt.

Make tunnel automation idempotent

CI systems retry jobs. Developers rerun failed commands. Agents repeat tool calls when they do not understand a response. Network timeouts can also leave the caller uncertain whether an operation succeeded. Without an idempotency strategy, one intended tunnel can become several live resources.

Idempotency means that repeating an instruction converges on the intended state instead of multiplying side effects. The exact Localtonet API fields available for lookup, naming, or metadata must be taken from current documentation. Even without assuming those fields, the controller can implement safe ownership and reconciliation principles.

Persist the returned tunnel identifier

After a successful create operation, capture the authoritative tunnel identifier returned by the supported interface. Pass it to later stages through a protected mechanism. Do not rediscover the tunnel by selecting the first item in a list, matching only a public hostname, or assuming that the newest resource belongs to the current run.

If the create request times out after being accepted, do not immediately create another tunnel. First reconcile current state using the documented API. The method used to correlate an existing resource depends on fields officially available at implementation time. If the API cannot safely correlate the uncertain operation, stop and request human review rather than deleting or reusing an arbitrary tunnel.

Distinguish ensure-running from create

A good controller expresses intent through operations such as “ensure the owned tunnel is running” and “ensure the owned tunnel is absent.” Internally, ensure-running can inspect known state, create only when no owned resource exists, start when necessary, and verify readiness. Ensure-absent can stop or delete only the exact resource recorded for that workflow.

This structure also makes retries safer. Repeating ensure-running should converge on one running resource. Repeating cleanup should tolerate a resource that is already stopped or absent, provided the documented API makes that state clear.

Do not retry every error

Retry transient transport failures with bounded attempts and delay. Do not blindly retry authentication failures, invalid targets, unsupported options, or malformed requests. Those conditions require corrected configuration. A controller should also enforce an overall deadline so that a broken environment does not remain exposed while a job waits indefinitely.

Because exact Localtonet response codes and retry guidance are not established in the supplied evidence, implementations must classify errors using current API documentation. The durable rule is to retry only conditions documented or reasonably identified as transient, and to preserve the original failure for diagnosis.

Use platform webhooks as observed-state signals

Localtonet provides platform-wide Token/Tunnel webhooks. These fire when a token or tunnel in a selected Token Group changes to Connected or Disconnected. The webhook sends a WebHookRequest JSON body with four documented properties:

{
  "Id": "tunnel id or auth token",
  "ActionDate": "event action date",
  "Type": "Token or Tunnel",
  "Status": "Connected or Disconnected"
}

The Id represents a tunnel ID or authentication token according to the event type. Type is either Token or Tunnel, and Status is either Connected or Disconnected. ActionDate provides the event’s action date.

Keep this platform webhook system distinct from File Server webhooks. File Server webhooks concern file-level upload, delete, rename, and move events and support optional path filtering and HMAC signing. Those file events are not a tunnel lifecycle feed and should not be used as one.

Do not assume platform webhook signing

The supplied documentation establishes HMAC signing for File Server file-event webhooks, but it does not establish an equivalent signing mechanism for platform-wide Token/Tunnel webhooks. Do not claim or implement a guessed signature header. Consult current Localtonet documentation for any updated verification options.

Process webhook deliveries defensively

A webhook receiver should validate the JSON structure, accept only known Type and Status values, and correlate the identifier with a resource the workflow actually owns. Unknown identifiers should not trigger broad corrective actions. Record enough metadata for troubleshooting, but do not log a device token if a token event places that sensitive value in Id.

Make event processing idempotent. The receiver should tolerate duplicate information and avoid starting a second workflow merely because the same state is observed more than once. Use ActionDate as event context, but consult current documentation before assuming ordering guarantees, delivery guarantees, or a specific date representation.

A Connected event should wake or accelerate reconciliation, not replace it. After receiving the event, query current state through the documented interface when appropriate and perform the actual public health check. Similarly, a Disconnected event can trigger diagnostics or cleanup, but the controller should inspect whether the device, the tunnel, or both changed state.

Combine events with polling and deadlines

Event-only workflows can stall if the receiver is unavailable or if assumptions about delivery are incorrect. Polling-only workflows can create unnecessary delay and API traffic. A robust design uses webhooks as prompt notifications, documented API reads for reconciliation, and a bounded deadline for failure.

For example, after starting a tunnel, the controller can wait for a matching Tunnel Connected signal while periodically checking current state according to documented limits. Once platform state is satisfactory, it runs an application-specific health probe. If readiness does not arrive before the deadline, it records diagnostics and enters cleanup.

A safe CI pipeline architecture

CI pipeline using protected credentials, a temporary tunnel, external testing, webhook signals, and always-run cleanup.
The pipeline creates a temporary tunnel, tests through it, and revokes it on every exit path.

An ephemeral CI tunnel should exist for the shortest useful period. Build and start the application first, verify it locally, and only then establish public exposure. This prevents a pipeline from opening a route to an application that has not initialized or is listening on an unexpected target.

Recommended phase structure

1

Prepare the runner or reachable device

Ensure the Localtonet client is installed and running on the machine that hosts the service or can reach it. Retrieve credentials from the protected CI secret store without printing them.

2

Start and verify the local application

Launch the service using the project’s normal procedure. Test the local target directly. Fail before creating a tunnel if the service is not listening or its health check does not pass.

3

Resolve current Localtonet configuration

Select the intended device token and an available relay from current product data. Validate the tunnel family and target. Do not use a guessed server code, API path, payload property, or domain configuration.

4

Create and record the owned tunnel

Create the configuration through the documented REST API and immediately store the returned identifier in protected job state. Treat an ambiguous response as a reconciliation problem, not permission to create duplicates.

5

Start, observe, and probe

Start the tunnel explicitly. Wait for current-state confirmation or the relevant Connected event, then test the assigned public URL or host and port with a protocol-aware health check.

6

Run dependent tests

Pass the public address only to the stages that require it. Avoid publishing the address or any related credentials in public logs. Keep test authorization separate from tunnel control credentials.

7

Clean up in an unconditional finalizer

Stop or delete the exact owned tunnel even when tests fail, the job is cancelled, or readiness times out. Preserve the primary test failure while also reporting cleanup failures for operator follow-up.

The phase structure above is an automation design pattern, not a claim about a seven-operation Localtonet API. Each Localtonet action inside it must use current official API documentation.

Handle cancellation and runner loss

A finalizer handles normal failures only while the runner remains alive. It cannot execute after a hard termination, host failure, or lost network connection. For that reason, ephemeral environments benefit from a separate reconciler that can inspect recorded ownership and remove resources left by expired jobs.

The reconciler should use conservative rules. It must identify the exact resource, verify that its owning job has ended, and avoid deleting a tunnel merely because it appears old. The available API metadata for expressing ownership must be confirmed from current documentation rather than assumed.

Preserve diagnostic evidence safely

When a tunnel fails to become ready, retain timestamps, sanitized operation outcomes, the selected tunnel family, whether the device was observed connected, whether the tunnel was observed connected, and the result of the local and public probes. Do not retain tokens, unrestricted credentials, or sensitive request bodies.

Cleanup errors should not overwrite the original application or test error. Report both. An operator needs to know why the job failed and whether a resource might still require manual attention in the dashboard.

Constrain AI-agent tunnel management

AI agent limited by policy, scoped actions, credential brokering, expiration, approval, and audit logging.
An AI agent should receive narrow tunnel actions rather than direct access to reusable credentials.

The Localtonet MCP Server allows AI coding assistants to create, start, and stop tunnels. This shortens the path from “run my application locally” to “make this development endpoint reachable,” but an assistant should operate within explicit boundaries.

Require a clear intent before exposure

Before allowing a create or start action, the assistant should identify the target service, tunnel family, intended duration, and reason for public exposure. It should confirm that the application is already running locally and that the user expects the endpoint to become public.

A vague request such as “share this” is not enough when a workspace contains several services. The assistant should ask which service is intended rather than scanning for an open port and exposing the first result. It should also avoid exposing administrative interfaces, databases, debugging consoles, or folders unless the user has explicitly reviewed and approved that target.

Use an approval policy based on impact

Agent action Suggested policy Reason
Inspect local application health Allow within the approved workspace This can confirm readiness without creating public exposure
Create a tunnel configuration Require target validation and explicit scope Creation establishes a resource even though it does not start it
Start a tunnel Require user awareness or approval Starting makes the configured route available while the device is connected
Stop a tunnel Allow for a tunnel created by the current session, or request confirmation otherwise Stopping an unrelated tunnel can interrupt another user or workflow
Act on an unknown existing resource Require human review The assistant may not have enough context to establish ownership

Give the agent structured outcomes

Agents work more reliably when tool results clearly separate resource identity, requested action, observed state, and errors. The integration should avoid returning secrets. It should also make uncertainty visible. If a tool call times out, the assistant should reconcile state rather than automatically issuing another create request.

Do not teach an agent guessed Localtonet commands or fields. Tool schemas and current official documentation are the authority. If the available tool does not expose a required operation, the assistant should state that limitation and hand control to an approved API workflow or the dashboard.

End every session with a cleanup decision

An assistant-driven tunnel should not continue simply because the conversation ended. The workflow should establish whether the tunnel is temporary or intentionally retained. For temporary exposure, stop it when testing is complete. If the assistant cannot confirm cleanup, it should clearly tell the user which resource may still be active without revealing sensitive data.

MCP and the REST API are complementary

Use the MCP Server for supervised assistant actions and the REST API for deterministic controllers that need persisted state, reconciliation, and unattended cleanup. The dashboard remains useful for human review and recovery.

Troubleshoot by checking each layer

Tunnel incidents are easier to diagnose when each dependency is tested independently. Avoid deleting and recreating the tunnel before determining which layer failed. Repeated recreation can hide the original cause and leave duplicate resources.

The tunnel was created but has no public availability

First confirm that the tunnel was explicitly started. Creation does not start it. Then verify that the selected Localtonet client device is connected and that the workflow used the intended device-specific token. Check current Localtonet state through the documented interface rather than relying only on a prior create response.

The tunnel is Connected but the application check fails

Test the local target from the Localtonet client device. Confirm that the application is listening on the configured local IP address and port and that it responds using the expected protocol. A platform-level Connected state does not prove that the application itself is healthy.

For HTTP services, use a health endpoint that reflects required dependencies rather than checking only whether a socket opens. For raw TCP or UDP services, use a protocol-aware probe. If authentication is required, use a dedicated test credential and keep it separate from Localtonet control credentials.

No Connected or Disconnected webhook arrived

Confirm that the webhook is associated with the intended Token Group and that the receiver is reachable. Then reconcile through the documented API rather than waiting forever. Do not assume a delivery guarantee, retry schedule, event ordering contract, or signature mechanism that current documentation does not state.

The pipeline created duplicate tunnels

Inspect the point at which the original create response became ambiguous. The usual architectural problem is retrying creation without first reconciling whether the earlier request succeeded. Record authoritative tunnel identifiers immediately and structure retries around ensure-running behavior rather than repeating create blindly.

Cleanup failed

Preserve the resource identifier and sanitized error details, then surface a clear operator alert. Use the dashboard or documented REST API to review the resource. Never compensate for uncertainty by deleting similarly named or recently created tunnels that might belong to another workflow.

The relay value stopped working

Relay server and region values must come from current Localtonet product data. Do not permanently hardcode a value copied from an old example. Revalidate configured selections against the current dashboard or documented interface and account for any plan or deployment constraints shown there.

An agent wants an unsupported operation

The verified MCP scope in this article covers creating, starting, and stopping Localtonet tunnels. If an assistant needs another action, do not fabricate a tool call. Use the current REST API documentation or perform the action manually in the dashboard after confirming that it is supported.

Frequently asked questions

Does creating a Localtonet tunnel make it immediately available?

No. Creating a tunnel configuration does not mean it is running. The tunnel must be started explicitly, the selected client device must be connected, and the target service must be reachable. Automation should then verify the assigned public URL or host and port with an application-aware check.

Should a CI pipeline use the REST API or the Localtonet MCP Server?

The REST API is generally the better architectural fit for deterministic, unattended CI automation because the controller can persist identifiers, reconcile state, enforce deadlines, and perform cleanup. The Localtonet MCP Server is designed for supported actions initiated through AI coding assistants and is better suited to supervised development workflows.

Can one authentication token be copied into every pipeline?

A Localtonet authentication token identifies a specific client device and must be kept secret. Avoid broad sharing across unrelated projects and environments. Store required credentials in a protected secret system, scope access to the intended workflow, and never commit or print the token.

Can a Connected webhook replace a public health check?

No. A Connected event is a useful platform-state signal, but it does not prove that the target application is healthy or serving the expected behavior. Use the event to trigger reconciliation, then run a protocol-aware check through the assigned public address.

Are platform Token/Tunnel webhooks the same as File Server webhooks?

No. Platform-wide webhooks report Token or Tunnel changes to Connected or Disconnected for a selected Token Group. File Server webhooks report file-level events such as upload, delete, rename, and move. File Server webhooks support HMAC signing, but that fact must not be applied automatically to platform lifecycle webhooks.

Should an ephemeral tunnel be stopped or deleted?

Stop the tunnel whenever public exposure is no longer needed. Delete it when the workflow owns the configuration, the tunnel is intended to be ephemeral, and there is no reason to retain it. If a configuration is deliberately reused, stopping it may be sufficient. Ownership should be established before either action.

Can automation hardcode a Localtonet relay server code?

Automation should obtain and validate relay server or region values from current Localtonet product data. Articles and templates should not guess or permanently hardcode server codes because available values can vary by plan, client version, region, or deployment.

Does Localtonet remove the need for application authentication?

No. Localtonet provides connectivity to the configured target. The exposed application still needs appropriate authentication, authorization, least-privilege access, and safe handling of sensitive data. Expose only the service and duration required for the workflow.

Build a controlled tunnel workflow with Localtonet

Start by connecting the intended device, validating the local service, and designing explicit create, start, verify, stop, and cleanup states. Use current Localtonet documentation for exact REST API details, or connect the Localtonet MCP Server when an approved coding assistant needs supervised tunnel control.

Get Started Free →

Localtonet is a secure multi-protocol tunneling and proxy platform designed to expose localhost, devices, private services, and AI agents to the public internet supporting HTTP/HTTPS tunnels, TCP/UDP forwarding, mobile proxy infrastructure, file server publishing, latency-optimized game connectivity, and developer-ready AI agent endpoint exposure from a single unified control plane.

support