Skip to Content
Documentation10 · Developer extensionsMCP connection and AI development
On this page

MCP connection and AI development

AI clients use MCP to query and configure TGateway and retrieve its matching development skill. Connect to the TGateway management address followed by /mcp using Streamable HTTP.

Connect from Codex

This example uses http://127.0.0.1:16100 as the TGateway management address. Replace the address and port with your deployment values. For a service on another computer, use its reachable IP address or domain.

  1. Confirm that TGateway is running and its management page opens on your computer.
  2. Open Settings → MCP servers → Add server.
  3. Enter the server settings below, save, and restart the connection if prompted.
ParameterDescription
NameUse a recognizable name, such as tgateway. Use different names for different gateways.
TransportSelect Streamable HTTP.
URLAppend /mcp to the management address: http://127.0.0.1:16100/mcp in this example.

Users do not need to locate or copy Bearer tokens or enter an Authorization header manually. Adding a server does not necessarily open a browser immediately; authentication is a separate action.

The CLI can also add and authenticate the server:

codex mcp add tgateway --url http://127.0.0.1:16100/mcp codex mcp login tgateway

Browser authorization

  1. Select Authenticate beside the server. In the browser, verify that the application is your MCP client and the service address identifies the target gateway. The page follows the browser language, using Chinese or English.
ParameterDescription
ApplicationThe MCP client requesting access; Codex in this example.
Service addressThe gateway MCP address being authorized. It should match the URL used when adding the server.
Return after authorizationA callback address generated by the client. You do not need to enter or copy it.
AccountYour existing TGateway management account.
PasswordThe password for that management account.
  1. Enter the account and password, then select Sign in and authorize. The connection uses that account’s permissions.
  2. When the browser displays Authentication complete. You may close this window., close the page and return to Codex. Codex provides this result page and handles credential exchange and refresh.

Codex confirmation after receiving the TGateway authorization callback

  1. Confirm that the server’s tools have loaded in Codex. Start with a query to verify the target, for example:

    Use the tgateway MCP server to list the current channels. Only query; do not change any configuration.

Permissions and credentials

Tools are generated from TGateway’s registered WebAPI endpoints, including queries, paging, creation, updates, deletion, imports, exports and other business operations. The available scope depends on this gateway’s registered endpoints and account permissions.

The MCP entry point validates identity. Each tool call also runs the original WebAPI permission checks and input validation. Listing a tool does not grant permission to execute it. Account disabling and session revocation remain effective.

Clients receive independent MCP credentials. Authorization codes are single-use and bound to the client, exact callback, service resource and PKCE proof. Refresh credentials rotate; replaying the previous refresh credential revokes that authorization. Server restarts require a new login. Clients should remove credentials on disconnect or revocation.

Existing automation can still send an existing business Bearer token to /mcp. Browser authorization is the normal user connection workflow.

Get the development skill through MCP

TGateway embeds the tgateway-development skill in its application assembly and delivers contracts and examples matched to the gateway version. AI can use the deployed instance to develop expressions, scripts, custom nodes, rule flows, collection plugins and data-forward plugins without product source code.

Read the entry point and select references

  1. Authenticate the MCP connection and query the gateway version and existing resources to verify the target.
  2. Find the tool corresponding to GetDevelopmentSkillFile in the instance’s tool catalog. Use its actual name; do not invent a prefix. Omit path to read the default SKILL.md entry.
  3. Read path: "manifest.json" and check gatewayVersion, targetFramework, pluginGenerator and the example indexes.
  4. Read references/runtime-contracts.md, then only the references needed for the task. Use references/validation.md for saving, compiling, binding and verification. Avoid loading every example into each conversation.

Example skill-file tool arguments:

{"path":"references/collect-plugins.md"}
FilePurpose
SKILL.mdEntry, task selection, code shapes and deliverables; returned when path is omitted.
manifest.jsonGateway version, target framework, plugin generator and example indexes.
references/runtime-contracts.mdPublic types, variable access, dependencies and lifecycle.
references/validation.mdSaving, compiling, binding, execution and result checks through the instance.
examples/index.jsonScript and node examples; read the required .cs.txt files.
examples/plugins/index.jsonIndependent plugin project and collection/forwarding example files.

Clients supporting ordinary HTTP API calls can use these paths at the same management address. Skill text and ZIP files are public development resources and their HTTP endpoints allow anonymous access. MCP connections still authenticate as described above; configuration, compilation and debugging retain their own permission checks:

GET /api/gatewayscriptcontroller/getdevelopmentskillfile GET /api/gatewayscriptcontroller/getdevelopmentskillfile?path=manifest.json GET /api/gatewayscriptcontroller/downloaddevelopmentskill

The first two read text; the last downloads the complete skill ZIP. The ZIP delivers tools/TGateway.PluginsGenerator.dll; the text-file tool cannot read that binary. Restore MCP downloads using bodyBase64, contentType and contentDisposition. If the client cannot handle binary downloads, use an authorized ordinary HTTP download.

AI can follow the retrieved skill in the current conversation without installing it locally. For ongoing local use, extract the complete package and follow the AI client’s own skill discovery mechanism. Recheck the manifest and retrieve matching resources when changing gateways or versions. The skill ZIP does not contain the full product runtime, and MCP does not grant access to the server’s filesystem.

Skill coverage

TaskReferences and deliverables
Read/write expressions and memory variablesreferences/expressions.md: DataTrans, MemoryVariableDatatrans, conversion and before-read/after-write extension selection.
Dynamic upload modelsreferences/models-and-storage.md: four DynamicModel_* types for variables, devices, alarms and plugin events.
Relational and time-series scriptsreferences/models-and-storage.md: four DynamicSQL_* types and TimeSeriesSQL_VariableBasicData.
MQTT RPC and complete source scriptsreferences/mqtt-and-fullsource.md: MQTTDynamicRPC, FullSource, arguments, results and required code shapes.
Custom nodesreferences/custom-nodes.md: input/output/in-out parameters, InitAsync, ChangedAsync, StopAsync, state and event cleanup.
Rule enginereferences/rule-engine.md: live node catalog, stable typeId and ports, rule JSON packages, validation, saving and reload verification.
Collection pluginsreferences/collect-plugins.md: base classes, channels, read packing, writes, passive reports, cancellation and lifecycle.
Data-forward pluginsreferences/data-forward-plugins.md: group scope, four model families, scripts/templates, batch upload, retry cache and replay.
Properties and special methodsreferences/plugin-properties-and-methods.md: dynamic/variable properties, generated catalogs, arguments, method variables and locks.
Project, packaging and deploymentreferences/plugin-build-and-deploy.md: release DLL references, Analyzer generator, net10.0, dependencies and PluginDlls installation/restart.
Communication and performancereferences/communication-debugging.md: subject identity, reads/writes, special methods, packet monitoring, failure recovery, replay and load measurement.

Code must match its entry point: expressions use method bodies, dynamic SQL entries use class members, FullSource uses a complete file, web custom nodes use node members, and plugins use independent DLL projects. See Script Development, Custom Node Development, Collection Plugin Development and Business Plugin Development.

Build and deploy a plugin

  1. Read the plugin references and examples/plugins/index.json, then download the ZIP. It includes Modbus collection, batch HTTP forwarding and a project example. Save the indexed files without their .txt suffixes.
  2. Obtain release DLLs and XML documentation from the same version and delivery build as the target gateway. Build with a net10.0 SDK, setting GatewayRuntimeDir to the runtime directory and GatewaySkillDir to the extracted skill directory. Load the generator as an Analyzer and check generated catalogs and diagnostics.
  3. Package the plugin DLL, necessary third-party dependencies, configuration examples, version and validation notes. Use Private=false for host references; exclude host core DLLs, credentials and databases.
  4. Stop the owned test instance, install DLLs at the top level of PluginDlls under its project data root, then start it. The location depends on ProjectDirectory and is not necessarily beside the executable. Subdirectories are not scanned. Do not replace loaded assemblies while running.
  5. Open Development configuration → Plugin management, filter by name and verify type, version and enabled state before creating a collection device or forwarding target.

External DLLs require gateway dynamic-loading support. Web script compilation is not plugin installation. An MCP connection without matching release DLLs permits discovery and documentation retrieval, but does not establish that a plugin has been built or installed.

Build the bundled project with these commands, replacing paths with actual directories. Use the same target framework and MSBuild properties for restore and build:

$env:DOTNET_ADD_GLOBAL_TOOLS_TO_PATH = 'false' dotnet restore ./PlantGatewayPlugins.csproj -p:GatewayRuntimeDir=C:/GatewayRuntime -p:GatewaySkillDir=C:/Skills/tgateway-development dotnet build ./PlantGatewayPlugins.csproj -c Release --no-restore -p:GatewayRuntimeDir=C:/GatewayRuntime -p:GatewaySkillDir=C:/Skills/tgateway-development -p:EmitCompilerGeneratedFiles=true

The environment setting affects only the current process and children. The generator is a build-time tool and does not belong in PluginDlls. Verify third-party dependency resolution in an isolated deployment instead of replacing host core libraries.

Verify communication and business behavior

  1. Select the device in Collection configuration and check live values, quality and collection times. Open Protocol debug → Special methods, select a catalog method and enter JSON arguments. The example reads 40001 with ReadScaledInt16, applies a scale of 0.1 and returns 23. Use the actual address syntax and methods of your plugin.

  2. For MCP debugging, query the tool corresponding to GetSubject. Identify the object with subjectType (CollectDevice or DataForwardTarget) and its real subjectId, then choose an advertised module. The host injects CancellationToken; do not include it in business arguments. Check business isSuccess, errors and returned values; HTTP 200 alone is insufficient.

  3. Ordinary address reads/writes verify the protocol layer. Verify variable transformations and before/after steps through variable writes and readback. BatchRead currently executes per address and does not measure background read packing.

  4. In Data forwarding, check group scope, trigger interval, batch size, target health and pending count. The example forwards 20 group variables every second. Target variable properties do not add out-of-scope variables. Verify requests, record counts and content at the receiver as well.

  5. Use a controlled receiver to verify rejection, timeout, disconnect, recovery and restart replay. CacheEnable controls retention for failed retries; it does not mean normal operation bypasses CacheDB. Retries can duplicate deliveries, so use business-key idempotency. In-memory batches not yet persisted can be lost on a forced process termination.

  6. Record variable counts, cycles, packing/splitting, requests, latency, failure rate, CPU and allocations. Reuse clients and group-produced data; avoid per-variable communication, global scans, repeated serialization, unbounded concurrency and permanent packet tracing.

If the client rejects a required array or scalar because a JsonElement field is described as object, preserve the error instead of changing the payload to an invalid business shape. Verify through an authorized HTTP API or the UI, and report that this does not prove the strict client’s MCP call passed.

Example task prompt

Connect to this TGateway MCP and read GetDevelopmentSkillFile's SKILL.md and manifest.json. Use only the instance tool catalog, retrieved skill and matching release DLLs; do not read product source. Load task-specific references/examples, and query existing devices, variables, scripts and node catalogs. Build workshop Modbus collection and batch HTTP forwarding: pack contiguous registers within protocol limits, forward only the chosen group's variables, retain failed batches and verify recovery replay. Build and verify discovery, configuration, communication and restart in an isolated test instance with a simulator. Deliver the project, plugin package, configuration steps, measured results and untested scope. Do not write to production devices.

Replace the business requirement with temperature conversion, an alarm node/rule flow or a custom storage script as needed. Supply actual variable names, units, triggers and expected results. Generated code still requires compilation and business validation. Scripts and plugins execute with the gateway process’s permissions.

Verify actions and logs

  1. Query status or the current identity and confirm the target gateway instance.
  2. Create a disposable test configuration, read and update it, then delete it.
  3. In operation logs, Request Source is MCP for tool calls or WebApi for ordinary HTTP API calls, including the management frontend.
  4. Variable and plugin-method RPC logs distinguish the same sources.

Logs follow the existing asynchronous recording policy. Not every query creates an operation log. Successful Gateway RPC recording also depends on the RPC success log setting.

File uploads use _http.bodyBase64. Downloads return bodyBase64, contentType and contentDisposition. Original API limits and MCP body limits still apply.

Domains and reverse proxies

Direct connections use the request’s IP or domain and protocol automatically. A reverse proxy preserves the external Host and passes the external host and protocol through X-Forwarded-Host and X-Forwarded-Proto, so no separate service address is required. The proxy must overwrite incoming headers with a single value.

To fix the public address explicitly, optionally configure Mcp:PublicOrigin. This setting takes precedence over the request address and forwarding headers:

{ "Mcp": { "PublicOrigin": "https://gateway.example.com" } }

The value contains only scheme, host and optional port. Preserve /.well-known/oauth-protected-resource/mcp, /.well-known/oauth-authorization-server, /mcp and /mcp/oauth/ at the public origin.

Troubleshooting

SymptomAction
No browser after adding a serverSelect Authenticate, or run codex mcp login <name>.
The browser displays Authentication completeCodex has received the authorization callback. Close the page and return to the client. Codex provides this result page.
No authentication action or a missing Bearer errorRun an OAuth-capable server version. Remove previously configured static Authorization headers or login helper scripts, restart the connection, then authenticate.
Authorization page is unavailableCheck the management URL, port and discovery paths. For a proxy, check forwarding headers; if a fixed public address is configured, check Mcp:PublicOrigin.
Tool access is deniedGrant the required API permission and reauthenticate.
Tool reports a business errorCheck the structured status and message, input, current gateway configuration and business restrictions. HTTP success does not prove a device action succeeded.
Skill tool is missingVerify the connection targets TGateway, the deployment includes the development-skill API, and refresh the client tool catalog.
Skill or plugin references do not matchRetrieve the manifest and ZIP from the target instance, and use its matching release DLLs. Do not mix assemblies from different builds.
NuGet assets lack a .NET 10 targetproject.assets.json was not restored for the current net10.0 target. Check the SDK, project path and conditional properties, restore using the same MSBuild parameters, then build. Do not skip the missing restore with --no-restore or downgrade the framework.
Credentials fail after restartingAuthenticate again.