concept ~7 min
Pipe Context Protocol (PCP)

- [Overview](#overview)

Pipe Context Protocol (PCP)

Table of Contents

Overview

Pipe Context Protocol (PCP) is TPipe’s unified function-calling system. It lets an LLM invoke approved tools—shell commands, HTTP calls, Python scripts, or native Kotlin functions—through a single, validated interface. Every tool the model can reach is declared in a PcpContext, which is then attached to a pipe before generation.

Key traits:

  • Declarative: you describe the allowed actions once; the runtime enforces them everywhere.
  • Transport-agnostic: irrespective of tool type, requests flow through a single dispatcher.
  • Guarded: all executors share common validation and per-transport security layers.

Transports and Executors

Each transport is backed by an executor that implements the PcpExecutor interface.

TransportExecutor classTypical usage
StdioStdioExecutorShell commands, CLIs, interactive sessions
HttpHttpExecutorREST APIs, webhooks, internal services
PythonPythonExecutorAd-hoc scripts, analysis, automation
KotlinKotlinExecutorJVM scripting, type-safe code execution
JavaScriptJavaScriptExecutorNode.js scripts, npm packages, async I/O
TpipePcpFunctionHandlerRegistered Kotlin functions and lambdas

PcpExecutionDispatcher chooses the executor based on the populated portion of the PcPRequest. The dispatcher also aggregates results when a response contains multiple requests.

See Also: PCP Kotlin and JavaScript Support for detailed coverage of Kotlin and JavaScript scripting.

Building a PCP Context

PcpContext collects the transports you want to expose and optional filesystem restrictions.

import com.TTT.PipeContextProtocol.PcpContext
import com.TTT.PipeContextProtocol.StdioContextOptions
import com.TTT.PipeContextProtocol.HttpContextOptions
import com.TTT.PipeContextProtocol.PythonContext
import com.TTT.PipeContextProtocol.Permissions

fun buildContext(): PcpContext {
    val context = PcpContext()

    // Shell access: read-only `ls`
    val ls = StdioContextOptions().apply {
        command = "ls"
        permissions.add(Permissions.Read)
        description = "List directory contents"
        timeoutMs = 5_000
    }
    context.addStdioOption(ls)

    // HTTP access: GitHub API
    val github = HttpContextOptions().apply {
        baseUrl = "https://api.github.com"
        endpoint = "/repos/owner/repo"
        method = "GET"
        allowedMethods.add("GET")
        allowedHosts.add("api.github.com")
        permissions.add(Permissions.Read)
        description = "Fetch repository metadata"
    }
    context.addHttpOption(github)

    // Python execution sandbox
    context.pythonOptions = PythonContext().apply {
        pythonPath = "/usr/bin/python3"
        workingDirectory = "/home/app/analysis"
        availablePackages.addAll(listOf("json", "statistics"))
        permissions.addAll(listOf(Permissions.Read, Permissions.Execute))
        timeoutMs = 30_000
    }

    // Restrict filesystem scope when commands reference paths
    context.allowedDirectoryPaths.addAll(listOf(
        "/home/app",
        "/tmp"
    ))
    context.forbiddenDirectoryPaths.add("/home/app/secrets")

    return context
}

Context Option Reference

StdioContextOptions

FieldPurpose
commandBinary or script to run.
argsDefault arguments (overridden by request arguments if provided).
permissionsAllowed actions (Read, Write, Execute, Delete).
descriptionNatural-language instruction for the model.
executionModeONE_SHOT, INTERACTIVE, CONNECT, or BUFFER_REPLAY.
sessionId/bufferIdRouting for CONNECT or BUFFER_REPLAY modes.
workingDirectoryExecution directory.
environmentVariablesKey/value pairs injected into the process.
timeoutMsMillisecond timeout for the operation.
keepSessionAliveLeave the process running after command completion.
bufferPersistencePersist interactive IO to buffers managed by StdioBufferManager.
maxBufferSizeMaximum bytes captured from stdout/stderr per execution.

TPipeContextOptions

FieldPurpose
functionNameRegistry key returned by FunctionRegistry.
descriptionPrompting hint for the LLM.
paramsMap of parameter metadata (ParamType, description, enum values).

Populate this via TPipeContextOptions.fromFunctionSignature or PcpContext.bindFunction to ensure parameter metadata stays in sync with registered functions.

HttpContextOptions

FieldPurpose
baseUrlScheme and host portion of the URL.
endpointPath/query segment appended to baseUrl.
methodHTTP method (e.g. GET, POST).
requestBodyDefault body payload.
allowedMethodsOptional allowlist enforced by HttpSecurityManager.
headersDefault headers.
authType"", "BASIC", "BEARER", or "APIKEY".
authCredentialsCredential map keyed by type (e.g. token, username, password).
allowedHostsHost allowlist for SSRF protection.
followRedirectsWhether redirects are permitted.
timeoutMsRequest timeout in milliseconds.
permissionsRequired permission set (typically Read / Write).
descriptionLLM-facing explanation of the endpoint.

PythonContext

FieldPurpose
availablePackagesWhitelist of importable top-level packages.
pythonVersionOptional version hint (major.minor prefix).
pythonPathInterpreter path.
workingDirectoryDirectory resolved before script execution.
environmentVariablesEnvironment injected into the interpreter process.
timeoutMsMaximum runtime.
captureOutputWhether stdout/stderr should be returned.
permissionsRequired permissions (e.g. Read, Execute).

KotlinContext

FieldPurpose
allowedImportsWhitelist of allowed import statements.
blockedImportsBlacklist of forbidden import statements.
allowedPackagesWhitelist of allowed package prefixes.
blockedPackagesBlacklist of forbidden package prefixes.
allowTpipeIntrospectionWhether to expose PcpRegistry and PcpContext to scripts.
allowHostApplicationAccessWhether to expose custom bindings to scripts.
exposedBindingsMap of binding names to descriptions for custom objects.
allowReflectionWhether reflection API usage is permitted.
allowClassLoaderAccessWhether ClassLoader access is permitted.
allowSystemAccessWhether System class access is permitted.
timeoutMsMaximum runtime in milliseconds.

JavaScriptContext

FieldPurpose
nodePathPath to Node.js executable (defaults to “node” in PATH).
allowedModulesWhitelist of npm modules that can be required.
workingDirectoryDirectory for script execution.
environmentVariablesEnvironment variables passed to Node.js process.
permissionsRequired permissions (e.g. Read, Execute).
timeoutMsMaximum runtime in milliseconds.

For detailed Kotlin and JavaScript configuration, see: PCP Kotlin and JavaScript Support

Applying PCP to a Pipe

Attach the context to a pipe so the dispatcher can evaluate model tool calls.

import com.TTT.PipeContextProtocol.PcpContext
import com.TTT.Pipe.Pipe

fun configurePipe(pipe: Pipe) {
    val context = buildContext()
    pipe.setPcPContext(context)
}

When you subsequently call pipe.generateText() or pipe.execute(), the runtime serialises the context into the system prompt. Any PCP requests produced by the LLM will be validated against the same context. To process PCP replies, call Pipe.processPcpResponse(llmResponse) after getting the LLM response.

PCP Requests and Responses

Request structure

PcPRequest contains four context option blocks plus an optional positional-argument list:

{
  "stdioContextOptions": {
    "command": "ls",
    "executionMode": "ONE_SHOT"
  },
  "argumentsOrFunctionParams": ["-la"],
  "httpContextOptions": {},
  "tPipeContextOptions": {},
  "pythonContextOptions": {}
}

PcpExecutionDispatcher.executeRequests takes a list of requests and returns a PcpExecutionResult comprised of individual PcpRequestResult entries. Each result records success, output, elapsed time, transport, and an optional error message.

Request parsing

Use PcpResponseParser when you need to extract PCP payloads from an LLM response directly. The parser repairs common JSON issues and validates that each request contains the minimum context needed for the chosen transport.

Security Layers

Each executor applies dedicated safeguards on top of the base context:

  • CommandSecurityManager enforces command classification, validates arguments, screens filesystem access against PcpContext allow/deny lists, and detects injection patterns.
  • HttpSecurityManager checks permissions, required host/method allowlists, request sizes, and blocks requests to private network destinations by default.
  • PythonSecurityManager enforces security levels, script-size limits, package whitelists, and blocks dangerous imports/functions unless specifically allowed.
  • ReturnValueHandler and FunctionInvoker ensure native function parameters and return values are converted safely between PCP wire types and Kotlin types.

Next Steps

Basic PCP Usage - Getting started with PCP