libtmux-swift MCP server
Commit Nov 15, 2026Allows an AI client to drive tmux sessions, windows, and panes using the Swift programming language.
Also known as libtmux/libtmux-swift
- Stars
- 1
- Tools
- —
- Downloads, 30 days
- —
- Latest version
- —
- Last commit
- Nov 15, 2026
- License
- MIT
What is libtmux-swift MCP?
libtmux-swift allows an AI client to drive tmux sessions, windows, and panes using the Swift programming language.
Summary generated from the project's README
About libtmux-swift MCP server
Managing terminal multiplexer environments through Swift code is what libtmux-swift enables for developers building automation tools. This server allows an AI client to interact with tmux sessions, windows, and panes by providing a structured way to query and modify terminal states. It is designed for users building session managers, test harnesses, or autonomous agents that require a reliable place to execute commands and monitor output.
Users can interact with a local tmux server or specify a particular socket via LIBTMUX_SOCKET_PATH or LIBTMUX_SOCKET. The library provides concrete tools like Server.sessions() to list active sessions, Server.snapshot() to capture a complete view of the environment, and Server.run() to execute arbitrary tmux commands. It supports Linux, WSL, and macOS, working with tmux versions ranging from 3.3a to 3.8 and the master branch. Every interaction explicitly reports TmuxError to ensure reliability when driving terminal workflows.
What you can do with it
- 1Automated session monitoringAn AI agent can check if a specific session exists before attempting to run commands within it.
- 2Command execution and observationAn AI client can send a command to a specific pane and read the resulting text output.
Written from the project's README. Every use case is checked against a quote from it.
Configuration
LIBTMUX_SOCKETLIBTMUX_TOOLSETS
Automated checks
Ran Nov 15, 2026Full report →Not verified yet. A server needs a score of 80, no serious finding, and enough data for us to check. How checks work · What to fix for more points
- Source repository linked and reachablelibtmux/libtmux-swift is public and reachablegithub.com/libtmux/libtmux-swift ↗Pass
- Package names this repository as its sourceNot checked
- Build provenance (Sigstore attestation)Not checked
- Open source license (OSI)MITspdx.org/licenses/MIT.html ↗Pass
- Commit or release in the last yearLast commit or release 2026-11-14github.com/libtmux/libtmux-swift ↗Pass
- OpenSSF ScorecardNot checked
- Package name not close to a popular packageNot checked
- No critical advisory in the package or its dependenciesNot checked
- No hidden instructions to the model0 tool descriptions and the README read; no override phrases, credential paths or hidden charactersPass
- Destructive tools are labelledNot checked
- Remote endpoint answers the MCP handshakeNot checked
README
View on GitHublibtmux for Swift
Drive tmux from Swift. A port of [libtmux][] for Python, in the same family of ports and holding to what that library established about tmux.
Ask a [Server][api-server] what it holds and get [Session][api-session],
[Window][api-window], [Pane][api-pane], and [Client][api-client] values
back. Every call reports [TmuxError][api-tmuxerror] explicitly.
It suits tools that drive tmux: a session manager, a test harness, a dashboard, an agent that needs somewhere to run things.
Everything that comes back is a value. A Session you hold is what the server
reported when you asked, and it stays that way when tmux changes. Ask again for
a newer view.
[!WARNING] Releases are numbered
0.1.N, and each release incrementsN. The API is not settled: any release may change or remove exported identifiers, and the changelog marks each break. Pin an exact version to avoid one.
Contents — Quick start · Install · Asking · Changing · Waiting · Modes · Workspaces · MCP · Testing · Products · Leaves out · Status · Docs · Tests
Quick start
With tmux already running, list its sessions. This is the whole program:
import LibTmux
let server = try Server()
for session in try await server.sessions() {
print(session.name, session.windowCount)
}
A [Server][api-server] built with no socket passes tmux neither -L nor
-S, so tmux picks the server: the one you are inside, and its default socket
elsewhere.
LIBTMUX_SOCKET_PATH or LIBTMUX_SOCKET names another, and
Server(socketPath:) or Server(socketName:) names one in code and leaves
both variables unread.
[Server.sessions()][api-server-sessions] asks it for every session. It runs on
Linux, including WSL, and on macOS (best effort, no CI),
with tmux 3.3a through 3.8, and master.
QuickStartTests spawns this program against a fixture server that holds one
session named quickstart, and checks that the output names it. It prints one
line per session: the name, then the window count.
Install
Depend on a release from 0.1.0 on:
.package(url: "https://github.com/libtmux/libtmux-swift.git", from: "0.1.0")
from: "0.1.0" accepts every 0.1.N and, in SwiftPM, any later minor release
below 1.0.0 as well, breaking releases included. Name a single release with
exact: and read the changelog before you move it.
.product(name: "LibTmux", package: "libtmux-swift")
[!NOTE] This page documents
master, which may be ahead of the latest release; the README at a release tag matches that release. To compile the examples on this page, depend onmaster:
.package(url: "https://github.com/libtmux/libtmux-swift.git", branch: "master")
YAMLWorkspaces: read YAML
Reading a workspace from YAML needs a parser, and asking for the trait is what
pulls one in. Without it nothing here resolves Yams; with it,
[Workspace.decode(yaml:)][api-workspace-decode-yaml] exists:
.package(
url: "https://github.com/libtmux/libtmux-swift.git",
from: "0.1.0",
traits: ["YAMLWorkspaces"]
)
Find sessions, windows, and panes
[Server.sessions()][api-server-sessions]: what tmux has now
One call asks tmux for every session. [Server.windows()][api-server-windows]
and [Server.panes()][api-server-panes] are its siblings, and each returns a
plain array of values:
let sessions = try await server.sessions()
let windows = try await server.windows()
let panes = try await server.panes()
QueryingTests runs this on a fixture server and asserts one session, one
window, and one pane.
[Pane][api-pane]: what is running in it
A pane knows its [Pane.currentCommand][api-pane-currentcommand] and
[Pane.currentPath][api-pane-currentpath]:
for pane in try await server.panes() {
print(pane.id, pane.currentCommand, pane.currentPath)
}
QueryingTests asserts the command is not empty and the path is absolute. It
prints one line per pane: the id, the command, and the path.
[Server.hasSession(_:)][api-server-hassession]: a yes-or-no question
Questions tmux answers with an exit code come back as a Bool:
guard try await server.hasSession("work") else { return }
QueryingTests runs both branches against a fixture server.
[Server.run(_:)][api-server-run]: anything the library does not model
A tmux command that runs and reports a nonzero status gives a reply:
has-session answers a question that way. run(_:) returns the status and the
text without throwing, and [TmuxCommand][api-tmuxcommand] builds the command:
let reply = try await server.run(
TmuxCommand("display-message", ["-p", "#{client_termname}"])
)
print(reply.isSuccess ? reply.text : reply.errorText)
QueryingTests runs it and asserts tmux did not answer unknown command. It
prints the client's terminal name, or tmux's error text when the command failed.
[Server.session(named:)][api-server-session-named]: one object, refreshed
Holding a value and wanting a newer view of it does not need a whole listing.
[Server.refresh(_:)][api-server-refresh] re-reads a value you hold:
let work = try await server.session(named: "work")
let fresh = try await server.refresh(pane)
LookupTests asserts the session is found by name and the pane by id.
A missing object is nil, because objects go away all the time. A re-read
also refuses a value from a different daemon: tmux restarts its ids at zero, so
a same-numbered pane on a replacement server is a different pane.
[Server.snapshot()][api-server-snapshot]: sessions, windows, panes, and clients at once
A [Snapshot][api-snapshot] collects all four into one value and resolves the
relationships inside it, so you do not match ids yourself:
let snapshot = try await server.snapshot()
for window in snapshot.windows(of: session) {
print(window.name, snapshot.panes(of: window).count)
}
SnapshotTests asserts every window of a session resolves back to it and has
panes. It prints each window's name and its pane count.
The listings are separate tmux commands. snapshot() checks the daemon
incarnation before and after them and reports a replacement. Another client can
still change the same daemon between listings, so the four lists can disagree.
[FilterExpr][api-filterexpr]: a filter that travels
Filter with the standard library when the predicate is local to your code.
FilterExpr is for a filter that has to leave it: stored in a config, sent to
another process, handed to a tool.
It is built from key paths, so the compiler rejects a text operator on a number, and it holds no closures, so it encodes:
let expression = try FilterExpr<Pane>.where(\.currentCommand, .isIn(["nvim", "vim"]))
let matching = try await server.panes().filter(expression)
FilteringTests asserts the expression selects the same panes the predicate
would. [Server.panes(where:)][api-server-panes-where] sends the same
expression through a tmux predicate that narrows the rows before they cross
the process boundary:
let matching = try await server.panes(where: expression)
LookupTests asserts it selects the pane the predicate would. The two give
the same answer:
- The first formats, pipes, and decodes every row before discarding most of them.
- The second lets tmux narrow the rows, then applies the full expression here.
- A regular expression cannot run in tmux. The predicate sent to tmux is widened, and this package's bounded regex engine decides the rest here.
The full vocabulary of operators, aliases, and field types is in
[Filtering.md][filtering] and on the [queries page][ref-concept-queries]. The
MCP tools accept session and window selectors; clients
apply other predicates to the returned metadata.
Change what tmux holds
[Server.newSession(named:windowName:)][api-server-newsession-named-startdirectory-windowname-width-height]: create and arrange
[Server.newSession][api-server-newsession-named-startdirectory-windowname-width-height]
makes a session.
[Server.newWindow(in:named:startDirectory:)][api-server-newwindow-in-named-startdirectory],
[Server.splitWindow][api-server-splitwindow], and
[Server.setOption][api-server-setoption-to-scope]
shape it, and [Server.run(_:in:)][api-server-run-in] sends a command to a
pane:
let session = try await server.newSession(named: "work", windowName: "editor")
_ = try await server.setOption("@purpose", to: "development", scope: .session(session))
let logs = try await server.newWindow(in: session, named: "logs").window
let pane = try await server.splitWindow(logs, direction: .right)
try await server.run("tail -f /tmp/build.log", in: pane)
ChangingTests asserts tmux ends up with a work session holding editor and
logs windows, and two panes in logs.
[Server.capture(_:)][api-server-capture-includinghistory]: read a pane back
Read a pane back the way a person would:
let lines = try await server.capture(pane)
ChangingTests prints a marker into a pane and asserts the capture holds it.
[TmuxCommandList][api-tmuxcommandlist]: several changes, one process
When several changes belong together, a command list spends one tmux invocation on all of them instead of one each:
var plan = TmuxCommandList()
for name in ["edit", "test", "logs"] {
plan = plan.then("new-window", ["-d", "-n", name])
}
_ = try await server.run(plan)
ChangingTests asserts every window the list names exists afterwards.
Type into a pane and wait
tmux has no hook that fires when a pane prints something, so a wait built from commands alone re-reads the pane on a timer and spends a process per tick.
A control connection is told instead. These three waits are cheaper than the loop everyone writes first; reach for them in this order.
[Server.wait(for:)][api-server-wait-for]: you wrote the command
Compose a channel into the command: tmux blocks server-side and returns on the
signal itself, so nothing is inferred from what the screen looks like.
[Server.shellInvocation][api-server-shellinvocation] names the tmux that
serves the pane:
try await server.run(
"make; \(server.shellInvocation) wait-for -S built",
in: pane
)
try await server.wait(for: "built")
WaitingTests runs it and asserts the wait returns when the command signals.
[FormatSubscription][api-formatsubscription]: the question is about state
Subscribe to a format and tmux reports changed values at most once a second,
with no capture or prompt regex. [ControlSession.watch][api-controlsession-watch]
subscribes and
[ControlSession.changes(named:)][api-controlsession-changes-named] yields the
changes:
try await server.connected(attachingTo: "work") { server, control in
try await control.watch(
FormatSubscription(
name: "cmd",
scope: .pane(pane.id),
format: "#{pane_current_command}"
)
)
for try await change in control.changes(named: "cmd") {
return change.value
}
return nil
}
WaitingTests asserts that the watch reports a value.
#{pane_current_command} names the foreground command; it does not prove a
submitted job has finished. Use a signalled channel for completion.
The connection needs tmux 3.7; an older daemon refuses it before anything attaches.
[Server.waitForOutput][api-server-waitforoutput-in-matching-stoppingat-requiringfreshoutput-startingat-timeout-taillimit]: you did not write the command
For a daemon printing ready or a dev server someone else started, wait on the
pane's output. %output wakes the wait, and the matching runs against the
rendered grid. [RegexPattern][api-regexpattern] values say what to match and
what to stop at:
let ready = try RegexPattern("Listening on")
let failed = try RegexPattern("EADDRINUSE|error", options: [.caseInsensitive])
let waited = try await server.waitForOutput(
in: pane,
matching: [ready],
stoppingAt: [failed]
)
WaitingTests asserts the wait ends .matched on the line it was given. A
small liveness check detects a pane removed while it is quiet. What to know:
- Stops. Pass
stoppingAtwhenever a failure marker exists. A build that fails after five seconds ends the wait at five seconds. - Already on screen. The condition is checked before it is blocked on, so
text already on screen returns at once with
matchedAtEntry: true. PassrequiringFreshOutputwhen only a new occurrence counts.
When a wait ends without a match, [OutputWait][api-outputwait] says which
thing happened:
timedOut,sawNewOutput: false. No new output was observed during the wait; this does not establish whether a command ran.timedOut, with output.tailholds what arrived, so you can fix the pattern against it.expiredWhileReading. The timeout ended before the pane could be read at all, so nothing was established either way.alternateScreen. A pager, editor, or other full-screen program held the pane. tmux fills it from a grid it keeps out of history, so matching is suppressed there.
The DocC catalogue's Waiting article explains why the output stream only
signals that the pane wrote something, and the match runs against the rendered
grid. The [waiting and retrying][ref-topic-waiting] page covers it on
libtmux.org.
Choosing how to reach tmux
[TmuxMode][api-tmuxmode]: one switch, the same answers
TmuxMode changes how work reaches tmux and never what you get back. It has two
settings, [TmuxMode.direct][api-tmuxmode-direct] and
[TmuxMode.connected(to:)][api-tmuxmode-connected-to]:
| Mode | How work travels | Where it wins |
|---|---|---|
.direct |
A tmux process per call | One call, or calls far apart. The default |
.connected(to:) |
One live connection for the whole scope | More than one call, and being told what changed |
.connected(to:) needs tmux 3.7 and .direct serves every supported release.
The default needs no word at all:
let sessions = try await server.sessions()
Each other mode adds one. [Server.using(_:_:)][api-server-using] runs a scope
in the mode you name, and the calls inside are the same calls with the same
types:
let names = try await server.using(.connected(to: "main")) { server in
try await server.sessions().map(\.name)
}
The mode is a value, so a program that decides at runtime can write the decision:
let mode: TmuxMode = shouldAttach ? .connected(to: "main") : .direct
let sessions = try await server.using(mode) { server in
try await server.sessions()
}
ModeTests asserts that a connected scope, and one chosen at runtime, return
what the direct one would.
[Server.using(_:_:)][api-server-using]: which server is in which mode
Three rules decide it, in order of precedence:
- The value you were handed. [
using(_:)][api-server-using] and [connected(attachingTo:_:)][api-server-connected-attachingto] give you a server in that mode. Nesting takes the innermost, so [using(.direct)][api-server-using] inside a connected scope keeps one call off the connection. - Anything else is
.direct, including a server captured from outside the closure. - Two calls take their own process regardless:
[
Server.wait(for:)][api-server-wait-for], which would otherwise deadlock the scope, and [Server.buffer(named:)][api-server-buffer-named], whose bytes a connection cannot report unambiguously. What comes back does not depend on the mode.
Nothing is global, and nothing is inherited by a task.
[server.mode][api-server-mode] reports which mode a value carries, so the rule
can be checked at runtime.
What it costs
swift run --package-path Benchmarks libtmux-bench measures each mode:
- It runs each scenario under each mode, behind a shim standing in for the tmux binary.
- It counts a process every time one starts and a round trip every time a command line is handed over.
- The benchmark writes the table below.
Scripts/update_mode_matrix.py --checkfails if it has drifted, and CI runs that check.
| Work | Direct | Connected |
|---|---|---|
| list-sessions, once | 2 processes, 2 round trips | 2 processes, 4 round trips |
| list-sessions, twenty times | 21 processes, 21 round trips | 2 processes, 23 round trips |
| sessions, windows, panes, clients, twice-checked | 7 processes, 7 round trips | 4 processes, 9 round trips |
| sessions, windows, panes, clients — one after another | 5 processes, 5 round trips | 2 processes, 7 round trips |
| the same four, concurrently — a pipelined batch | 5 processes, 5 round trips | 2 processes, 7 round trips |
| new-window five times, each its own command | 8 processes, 8 round trips | 2 processes, 10 round trips |
| the same five as one command list | 4 processes, 4 round trips | 2 processes, 6 round trips |
| new-window then split, read back | 6 processes, 6 round trips | 2 processes, 8 round trips |
| Noticing a pane printed a line | Polling | Streaming |
|---|---|---|
| tmux processes spent | 2 | 1 |
| round trips spent | 2 | 3 |
How to read the table:
- Directly, a round trip is a process, so that column always agrees with itself. Every row also carries the process that reads the daemon's release once.
- Connecting collapses the rest to the connection's own process and charges extra round trips for the attach and its release check. A single call is therefore where the default wins, and from the second call on the connection is ahead.
- A command list shows up in the round trips. Under a connection it and the separate commands cost the same processes, and only the round trips tell them apart.
The benchmark also prints wall-clock medians, which move with the machine. Run it yourself for those.
[Server.connected(attachingTo:_:)][api-server-connected-attachingto]: hear changes as they happen
A connection can do one thing a process cannot, which is report what changed without being asked. It needs tmux 3.7; an older daemon refuses it before anything attaches:
let firstLine: String? = try await server.connected(attachingTo: "work") { server, events in
for try await notification in events.notifications
where notification.name == "output" {
return notification.arguments
}
return nil
}
StreamingTests asserts the connection reports pane output as it happens.
[withTmuxError][api-withtmuxerror]: typed errors across a scope
Every call throws [TmuxError][api-tmuxerror] and says so, so a program can use
typed throws from top to bottom. The scoped forms take a closure, and Swift 6.2
cannot carry a closure's thrown type out of one. Wrap the scope to narrow it
back:
func names(_ server: Server) async throws(TmuxError) -> [String] {
try await withTmuxError {
try await server.using(.connected(to: "main")) { server in
try await server.sessions().map(\.name)
}
}
}
LookupTests asserts the scope returns the session names.
Swift 6.2 cannot do this for you: a typed-throws overload of the scopes is unreachable, because a closure literal's thrown type is never inferred from its body.
Workspaces, from a file or from Swift
[TmuxWorkspace][mod-tmuxworkspace] builds a whole session in one go, from a
[tmuxp][] workspace. Written in Swift, a workspace is ordinary values.
[Workspace][api-workspace]: a session described as values
[WindowPlan][api-windowplan] and [PanePlan][api-paneplan] describe each
window and its panes:
let workspace = Workspace(
sessionName: "work",
windows: [
WindowPlan(
windowName: "editor",
layout: "even-horizontal",
panes: [PanePlan(), PanePlan()]
),
WindowPlan(
windowName: "logs",
panes: [PanePlan(shellCommands: ["tail -f /tmp/build.log"])]
),
]
)
WorkspaceTests builds this value and asserts tmux ends up with its windows.
[WorkspaceBuilder.build(_:on:)][api-workspacebuilder-build-on]: build it on a server
let session = try await WorkspaceBuilder.build(workspace, on: server)
WorkspaceTests asserts the work session exists with editor and logs
windows and two panes in editor. What to know:
- A name in use is refused. Two callers building the same workspace should not silently share a session.
- A failure rolls back. A later, ordinary failure removes the exact session this build created; a rollback failure reports both errors.
- An interruption removes nothing. The signal that stopped the build could just as well stop the cleanup that would follow it.
[Server.validateLayouts(_:)][api-server-validatelayouts]: check layouts first
The builder validates every layout before creating the session. The same native
guard protects [Server.selectLayout(_:_:)][api-server-selectlayout] and MCP
[select_layout]. Custom builders can check a complete batch with the desired
pane counts first:
try await server.validateLayouts([("even-h", 2), ("tiled", 1)])
WorkspaceTests runs this call. The rules:
- Abbreviations. Names accept unique abbreviations for the running daemon's version.
- Saved layouts. They require a checksum, a nonempty tree, and enough cells; tmux still owns geometry and pruning.
- JSON layouts. The library refuses a JSON layout below tmux 3.8 with
TmuxError.invocationFailedbefore dispatching the layout command. A version probe may run first; the error names tmux 3.8. - An empty batch performs no I/O unless cancelled.
- A cold endpoint. A version-sensitive name on an unbound cold endpoint uses the configured tmux client; permission, protocol, and retained-connection errors propagate.
libtmux-swift MCP questions
What platforms does libtmux-swift support?
It runs on Linux (including WSL) and macOS.
Is the API stable?
No, the API is currently in alpha and is not settled; any release may change or remove exported identifiers.