feat: add official MCP service plugin
This commit is contained in:
commit
bdbd8f7701
14 files changed
+2417
No files matched your search
@@ -0,0 +1,27 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache-dependency-path: go.sum
|
||||
- name: Check formatting
|
||||
shell: pwsh
|
||||
run: |
|
||||
$files = gofmt -l (git ls-files '*.go')
|
||||
if ($files) { $files; exit 1 }
|
||||
- run: go test ./...
|
||||
- run: go vet ./...
|
||||
- run: go build -trimpath -o bin/reims-agent.exe ./cmd/reims-agent
|
||||
@@ -0,0 +1,66 @@
|
||||
name: Release plugin package
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
package:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache-dependency-path: go.sum
|
||||
- name: Build Windows sidecar
|
||||
run: |
|
||||
mkdir -p bin
|
||||
GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -o bin/reims-agent.exe ./cmd/reims-agent
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
repository: Nwflower/Reims-Go
|
||||
ref: main
|
||||
path: reims-go
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: reims-go/go.mod
|
||||
cache-dependency-path: reims-go/go.sum
|
||||
- name: Build headless Reims-Go plugin CLI
|
||||
shell: pwsh
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force -Path 'reims-go/cmd/reims-doctor' | Out-Null
|
||||
@'
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"github.com/Nwflower/reims-go/internal/cli"
|
||||
)
|
||||
|
||||
func main() { os.Exit(cli.Main(os.Args[1:])) }
|
||||
'@ | Set-Content -Encoding utf8 'reims-go/cmd/reims-doctor/main.go'
|
||||
$env:CGO_ENABLED = '0'
|
||||
go build -C reims-go -trimpath -o ../reims-go-plugin-cli.exe ./cmd/reims-doctor
|
||||
- name: Validate and package plugin
|
||||
id: package
|
||||
shell: pwsh
|
||||
run: |
|
||||
$tag = '${{ github.ref_name }}'
|
||||
$version = $tag.Substring(1)
|
||||
$manifest = Get-Content -Raw plugin.json | ConvertFrom-Json
|
||||
if ($manifest.version -ne $version) { throw "Tag $tag does not match plugin.json version $($manifest.version)" }
|
||||
.\reims-go-plugin-cli.exe plugin doctor .
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
.\reims-go-plugin-cli.exe plugin pack --out "reims.agent-$version.zip" .
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
$hash = (Get-FileHash "reims.agent-$version.zip" -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
"$hash reims.agent-$version.zip" | Set-Content -Encoding ascii "reims.agent-$version.sha256"
|
||||
"version=$version" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
|
||||
- name: Publish GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: gh release create "${{ github.ref_name }}" "reims.agent-${{ steps.package.outputs.version }}.zip" "reims.agent-${{ steps.package.outputs.version }}.sha256" --verify-tag --generate-notes
|
||||
@@ -0,0 +1,3 @@
|
||||
/bin/*.exe
|
||||
/dist/
|
||||
*.zip
|
||||
@@ -0,0 +1,200 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate acts) or agreed
|
||||
to in writing, shall any Contributor be liable to You for damages,
|
||||
including any direct, indirect, special, incidental, or consequential
|
||||
damages of any character arising as a result of this License or out of
|
||||
the use or inability to use the Work (including but not limited to damages
|
||||
for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 Reims-Go contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Reims-Go MCP Service
|
||||
|
||||
`reims.agent` is the official Reims-Go L3 plugin that exposes host-authorized virtual machine information and desktop controls to MCP clients. The host retains QMP access and permission checks. The plugin communicates with the host through `reims-go plugin connect reims.agent mcp`; it does not open a network listener.
|
||||
|
||||
## Development
|
||||
|
||||
Requirements are Go 1.26 or later and a Reims-Go checkout with plugin API 1.1 support.
|
||||
|
||||
```powershell
|
||||
go test ./...
|
||||
go vet ./...
|
||||
go build -o bin/reims-agent.exe ./cmd/reims-agent
|
||||
reims-go plugin doctor .
|
||||
reims-go plugin pack .
|
||||
```
|
||||
|
||||
Use the Reims-Go Plugins page to link this directory in developer mode. Configure an MCP client to launch `reims-go.exe plugin connect reims.agent mcp` over stdio. Grant the plugin permissions in Reims-Go before calling VM tools.
|
||||
|
||||
## Current MCP tools
|
||||
|
||||
- `vm_list`, `vm_get`, `vm_start`, `vm_shutdown`, and `vm_unlock`
|
||||
- `computer` for screenshots, zoom, pointer, keyboard, and text input
|
||||
- `wait_for_screen` for changed or stable frames
|
||||
- `guest_public_key`, `guest_wait_ready`, and `guest_trust_host` for explicit SSH setup and host-key pinning
|
||||
- `guest_exec`, `guest_put`, `guest_get`, and `guest_logs` for SSH commands, bounded SFTP transfers, and paged command output
|
||||
- `reims://vm/{ref}/screen` image resource
|
||||
|
||||
Screenshots are returned to the MCP client and are not retained by the plugin. The plugin package contains a native Windows sidecar and therefore runs with the current Windows account's permissions. Reims-Go presents the declared capabilities and requires approval before enabling them.
|
||||
|
||||
Guest SSH requires port forwarding and a configured username in the host VM settings. Review the fingerprint from `guest_wait_ready` before calling `guest_trust_host`, and add the returned public key to the guest account's `~/.ssh/authorized_keys`. SFTP transfers are limited to the guest user's home directory and 64 MiB per file.
|
||||
|
||||
## Releases
|
||||
|
||||
Tags named `vX.Y.Z` run the Windows CI, tests, vet, build the sidecar, and package the plugin with the Reims-Go CLI. The resulting `reims.agent-X.Y.Z.zip` and its SHA-256 are attached to the GitHub Release. Market registration is maintained separately in [reims-go/plugins](https://github.com/reims-go/plugins).
|
||||
|
||||
The L3 release workflow builds the executable from this public source repository. The binary is not committed to Git.
|
||||
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/reims-go/reims-agent/internal/mcp"
|
||||
"github.com/reims-go/reims-agent/internal/sidecar"
|
||||
)
|
||||
|
||||
func main() {
|
||||
tools := mcp.New()
|
||||
server := sidecar.New(tools)
|
||||
tools.BindHost(sidecar.HostClient{Server: server})
|
||||
if err := server.Serve(context.Background()); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
module github.com/reims-go/reims-agent
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/pkg/sftp v1.13.7
|
||||
golang.org/x/crypto v0.57.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||
github.com/pkg/sftp v1.13.7 h1:uv+I3nNJvlKZIQGSr8JVQLNHFU9YhhNpvC14Y6KgmSM=
|
||||
github.com/pkg/sftp v1.13.7/go.mod h1:KMKI0t3T6hfA+lTR/ssZdunHo+uwq7ghoN09/FSu3DY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
|
||||
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
|
||||
golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,647 @@
|
||||
package guest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
const MaxTransferBytes int64 = 64 << 20
|
||||
|
||||
type SSH struct {
|
||||
root string
|
||||
}
|
||||
|
||||
type ExecResult struct {
|
||||
ExitCode int `json:"exit_code"`
|
||||
TimedOut bool `json:"timed_out"`
|
||||
Output string `json:"output"`
|
||||
Truncated bool `json:"truncated"`
|
||||
LogID string `json:"log_id"`
|
||||
}
|
||||
|
||||
type HostKey struct {
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
Authorized string `json:"host_key"`
|
||||
}
|
||||
|
||||
type transferResult struct {
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
func NewSSH(root string) *SSH { return &SSH{root: root} }
|
||||
|
||||
func (s *SSH) PublicKey() (string, error) {
|
||||
signer, err := s.signer()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(ssh.MarshalAuthorizedKey(signer.PublicKey())), nil
|
||||
}
|
||||
|
||||
func (s *SSH) Probe(ctx context.Context, address string) (HostKey, error) {
|
||||
conn, err := s.dial(ctx, address)
|
||||
if err != nil {
|
||||
return HostKey{}, err
|
||||
}
|
||||
defer conn.Close()
|
||||
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
var offered ssh.PublicKey
|
||||
config := &ssh.ClientConfig{
|
||||
User: "reims-probe",
|
||||
HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
|
||||
offered = key
|
||||
return nil
|
||||
},
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
_, _, _, handshakeErr := ssh.NewClientConn(conn, address, config)
|
||||
if offered == nil {
|
||||
if handshakeErr == nil {
|
||||
return HostKey{}, errors.New("SSH server did not provide a host key")
|
||||
}
|
||||
return HostKey{}, fmt.Errorf("SSH handshake: %w", handshakeErr)
|
||||
}
|
||||
return hostKeyInfo(offered), nil
|
||||
}
|
||||
|
||||
func (s *SSH) TrustHostKey(vm, address, fingerprint string) error {
|
||||
return s.TrustHostKeyContext(context.Background(), vm, address, fingerprint)
|
||||
}
|
||||
|
||||
func (s *SSH) TrustHostKeyContext(ctx context.Context, vm, address, fingerprint string) error {
|
||||
observed, err := s.Probe(ctx, address)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if observed.Fingerprint != fingerprint {
|
||||
return fmt.Errorf("SSH host key changed during confirmation: expected %s, observed %s", fingerprint, observed.Fingerprint)
|
||||
}
|
||||
pins, err := s.readPins()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pins[vm] = fingerprint
|
||||
return s.writePins(pins)
|
||||
}
|
||||
|
||||
func (s *SSH) WaitReady(ctx context.Context, vm, address, username string, timeout time.Duration) (map[string]any, error) {
|
||||
if timeout <= 0 || timeout > 30*time.Second {
|
||||
return nil, errors.New("SSH wait timeout must be between 1 and 30000 milliseconds")
|
||||
}
|
||||
deadline := time.NewTimer(timeout)
|
||||
defer deadline.Stop()
|
||||
tick := time.NewTicker(500 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
var lastErr error
|
||||
for {
|
||||
key, err := s.Probe(ctx, address)
|
||||
if err == nil {
|
||||
pins, pinErr := s.readPins()
|
||||
if pinErr != nil {
|
||||
return nil, pinErr
|
||||
}
|
||||
if pins[vm] == "" {
|
||||
return map[string]any{
|
||||
"ready": false, "trust_required": true, "fingerprint": key.Fingerprint,
|
||||
"host_key": key.Authorized,
|
||||
"message": "Review the SSH host fingerprint and host key, then call guest_trust_host. Add plugin_public_key to the guest's ~/.ssh/authorized_keys before running commands.",
|
||||
}, nil
|
||||
}
|
||||
if pins[vm] != key.Fingerprint {
|
||||
return nil, fmt.Errorf("SSH host fingerprint changed for %s: pinned %s, observed %s", vm, pins[vm], key.Fingerprint)
|
||||
}
|
||||
client, dialErr := s.connect(ctx, vm, address, username)
|
||||
if dialErr == nil {
|
||||
_ = client.Close()
|
||||
return map[string]any{"ready": true, "fingerprint": key.Fingerprint}, nil
|
||||
}
|
||||
lastErr = dialErr
|
||||
} else {
|
||||
lastErr = err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-deadline.C:
|
||||
if lastErr != nil {
|
||||
return map[string]any{"ready": false, "message": lastErr.Error()}, nil
|
||||
}
|
||||
return map[string]any{"ready": false}, nil
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SSH) Exec(ctx context.Context, vm, address, username, command, cwd string, env map[string]string, timeout time.Duration) (ExecResult, error) {
|
||||
if strings.TrimSpace(command) == "" {
|
||||
return ExecResult{}, errors.New("command is required")
|
||||
}
|
||||
if timeout <= 0 || timeout > 30*time.Minute {
|
||||
return ExecResult{}, errors.New("command timeout must be between 1 millisecond and 30 minutes")
|
||||
}
|
||||
client, err := s.connect(ctx, vm, address, username)
|
||||
if err != nil {
|
||||
return ExecResult{}, err
|
||||
}
|
||||
defer client.Close()
|
||||
session, err := client.NewSession()
|
||||
if err != nil {
|
||||
return ExecResult{}, err
|
||||
}
|
||||
defer session.Close()
|
||||
logs := filepath.Join(s.root, "logs")
|
||||
if err := os.MkdirAll(logs, 0o700); err != nil {
|
||||
return ExecResult{}, err
|
||||
}
|
||||
logFile, err := os.CreateTemp(logs, "guest-exec-*.log")
|
||||
if err != nil {
|
||||
return ExecResult{}, err
|
||||
}
|
||||
logID := filepath.Base(logFile.Name())
|
||||
writer := &outputWriter{file: logFile}
|
||||
session.Stdout = writer
|
||||
session.Stderr = writer
|
||||
remote := shellCommand(command, cwd, env)
|
||||
if err := session.Start(remote); err != nil {
|
||||
_ = logFile.Close()
|
||||
return ExecResult{}, err
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- session.Wait() }()
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
timedOut := false
|
||||
select {
|
||||
case err = <-done:
|
||||
case <-ctx.Done():
|
||||
timedOut = true
|
||||
err = stopRemote(session, client, done)
|
||||
case <-timer.C:
|
||||
timedOut = true
|
||||
err = stopRemote(session, client, done)
|
||||
}
|
||||
closeErr := logFile.Close()
|
||||
if closeErr != nil {
|
||||
return ExecResult{}, closeErr
|
||||
}
|
||||
if err != nil && !timedOut {
|
||||
var exitErr *ssh.ExitError
|
||||
if !errors.As(err, &exitErr) {
|
||||
return ExecResult{}, err
|
||||
}
|
||||
}
|
||||
exitCode := 0
|
||||
if err != nil {
|
||||
var exitErr *ssh.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
exitCode = exitErr.ExitStatus()
|
||||
} else {
|
||||
exitCode = -1
|
||||
}
|
||||
}
|
||||
return ExecResult{ExitCode: exitCode, TimedOut: timedOut, Output: writer.result(), Truncated: writer.truncated(), LogID: logID}, nil
|
||||
}
|
||||
|
||||
func stopRemote(session *ssh.Session, client *ssh.Client, done <-chan error) error {
|
||||
_ = session.Signal(ssh.SIGTERM)
|
||||
timer := time.NewTimer(5 * time.Second)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case err := <-done:
|
||||
return err
|
||||
case <-timer.C:
|
||||
_ = session.Signal(ssh.SIGKILL)
|
||||
_ = client.Close()
|
||||
return <-done
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SSH) ReadLog(logID string, offset int64, limit int) (map[string]any, error) {
|
||||
if logID == "" || filepath.Base(logID) != logID || strings.ContainsAny(logID, `/\\`) || offset < 0 {
|
||||
return nil, errors.New("invalid guest log id or offset")
|
||||
}
|
||||
if limit <= 0 {
|
||||
limit = 8192
|
||||
}
|
||||
if limit > 64<<10 {
|
||||
return nil, errors.New("guest log page cannot exceed 65536 bytes")
|
||||
}
|
||||
file, err := os.Open(filepath.Join(s.root, "logs", logID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if offset > info.Size() {
|
||||
return nil, errors.New("guest log offset is past end of file")
|
||||
}
|
||||
if _, err := file.Seek(offset, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page, err := io.ReadAll(io.LimitReader(file, int64(limit)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
next := offset + int64(len(page))
|
||||
return map[string]any{"log_id": logID, "offset": offset, "next_offset": next, "eof": next >= info.Size(), "text": string(page)}, nil
|
||||
}
|
||||
|
||||
func (s *SSH) Put(ctx context.Context, vm, address, username, localPath, remotePath string) (transferResult, error) {
|
||||
info, err := os.Stat(localPath)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > MaxTransferBytes {
|
||||
return transferResult{}, fmt.Errorf("upload must be a regular file no larger than %d bytes", MaxTransferBytes)
|
||||
}
|
||||
client, err := s.connect(ctx, vm, address, username)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
defer client.Close()
|
||||
transfer, err := sftp.NewClient(client)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
defer transfer.Close()
|
||||
home, err := transfer.Getwd()
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
target, err := confinedPath(home, remotePath)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
if err := mkdirGuestPath(transfer, home, path.Dir(target)); err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
parent, err := transfer.RealPath(path.Dir(target))
|
||||
if err != nil || !withinGuestHome(home, parent) {
|
||||
return transferResult{}, errors.New("guest upload directory resolves outside the guest home directory")
|
||||
}
|
||||
target = path.Join(parent, path.Base(target))
|
||||
tempPath := target + ".reims-upload-" + fmt.Sprint(time.Now().UnixNano())
|
||||
remote, err := transfer.Create(tempPath)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
local, err := os.Open(localPath)
|
||||
if err != nil {
|
||||
_ = remote.Close()
|
||||
_ = transfer.Remove(tempPath)
|
||||
return transferResult{}, err
|
||||
}
|
||||
count, copyErr := io.Copy(remote, io.LimitReader(local, MaxTransferBytes+1))
|
||||
localErr := local.Close()
|
||||
remoteErr := remote.Close()
|
||||
if copyErr != nil || localErr != nil || remoteErr != nil {
|
||||
_ = transfer.Remove(tempPath)
|
||||
return transferResult{}, errors.Join(copyErr, localErr, remoteErr)
|
||||
}
|
||||
if count > MaxTransferBytes {
|
||||
_ = transfer.Remove(tempPath)
|
||||
return transferResult{}, fmt.Errorf("upload exceeds %d bytes", MaxTransferBytes)
|
||||
}
|
||||
if err := transfer.Rename(tempPath, target); err != nil {
|
||||
_ = transfer.Remove(tempPath)
|
||||
return transferResult{}, err
|
||||
}
|
||||
return transferResult{Bytes: count}, nil
|
||||
}
|
||||
|
||||
func (s *SSH) Get(ctx context.Context, vm, address, username, remotePath, localPath string) (transferResult, error) {
|
||||
client, err := s.connect(ctx, vm, address, username)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
defer client.Close()
|
||||
transfer, err := sftp.NewClient(client)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
defer transfer.Close()
|
||||
home, err := transfer.Getwd()
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
target, err := confinedPath(home, remotePath)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
resolved, err := transfer.RealPath(target)
|
||||
if err != nil || !withinGuestHome(home, resolved) {
|
||||
return transferResult{}, errors.New("guest download path resolves outside the guest home directory")
|
||||
}
|
||||
remote, err := transfer.Open(resolved)
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
defer remote.Close()
|
||||
info, err := remote.Stat()
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > MaxTransferBytes {
|
||||
return transferResult{}, fmt.Errorf("download must be a regular file no larger than %d bytes", MaxTransferBytes)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(localPath), 0o700); err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
local, err := os.CreateTemp(filepath.Dir(localPath), ".reims-download-*")
|
||||
if err != nil {
|
||||
return transferResult{}, err
|
||||
}
|
||||
tempPath := local.Name()
|
||||
count, copyErr := io.Copy(local, io.LimitReader(remote, MaxTransferBytes+1))
|
||||
closeErr := local.Close()
|
||||
if copyErr != nil || closeErr != nil || count > MaxTransferBytes {
|
||||
_ = os.Remove(tempPath)
|
||||
if count > MaxTransferBytes {
|
||||
return transferResult{}, fmt.Errorf("download exceeds %d bytes", MaxTransferBytes)
|
||||
}
|
||||
return transferResult{}, errors.Join(copyErr, closeErr)
|
||||
}
|
||||
if err := os.Rename(tempPath, localPath); err != nil {
|
||||
_ = os.Remove(tempPath)
|
||||
return transferResult{}, err
|
||||
}
|
||||
return transferResult{Bytes: count}, nil
|
||||
}
|
||||
|
||||
func (s *SSH) connect(ctx context.Context, vm, address, username string) (*ssh.Client, error) {
|
||||
if strings.TrimSpace(username) == "" {
|
||||
return nil, errors.New("SSH username is not configured for this VM")
|
||||
}
|
||||
pins, err := s.readPins()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fingerprint := pins[vm]
|
||||
if fingerprint == "" {
|
||||
return nil, fmt.Errorf("SSH host key is not trusted for %s; call guest_wait_ready and review the fingerprint", vm)
|
||||
}
|
||||
signer, err := s.signer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := s.dial(ctx, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
config := &ssh.ClientConfig{
|
||||
User: username,
|
||||
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
|
||||
HostKeyCallback: func(_ string, _ net.Addr, offered ssh.PublicKey) error {
|
||||
got := ssh.FingerprintSHA256(offered)
|
||||
if got != fingerprint {
|
||||
return fmt.Errorf("SSH host fingerprint changed for %s: pinned %s, observed %s", vm, fingerprint, got)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
clientConn, chans, reqs, err := ssh.NewClientConn(conn, address, config)
|
||||
if err != nil {
|
||||
_ = conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
_ = conn.SetDeadline(time.Time{})
|
||||
return ssh.NewClient(clientConn, chans, reqs), nil
|
||||
}
|
||||
|
||||
func (s *SSH) dial(ctx context.Context, address string) (net.Conn, error) {
|
||||
conn, err := (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "tcp", address)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect to guest SSH at %s: %w", address, err)
|
||||
}
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
|
||||
deadline = ctxDeadline
|
||||
}
|
||||
_ = conn.SetDeadline(deadline)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (s *SSH) signer() (ssh.Signer, error) {
|
||||
keyPath := filepath.Join(s.root, "keys", "id_ed25519")
|
||||
if data, err := os.ReadFile(keyPath); err == nil {
|
||||
return ssh.ParsePrivateKey(data)
|
||||
} else if !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(keyPath), 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, private, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
block, err := ssh.MarshalPrivateKey(private, "reims.agent")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encoded := pem.EncodeToMemory(block)
|
||||
if err := os.WriteFile(keyPath, encoded, 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ssh.ParsePrivateKey(encoded)
|
||||
}
|
||||
|
||||
func hostKeyInfo(key ssh.PublicKey) HostKey {
|
||||
return HostKey{Fingerprint: ssh.FingerprintSHA256(key), Authorized: string(ssh.MarshalAuthorizedKey(key))}
|
||||
}
|
||||
|
||||
func (s *SSH) readPins() (map[string]string, error) {
|
||||
file := filepath.Join(s.root, "keys", "known_hosts.json")
|
||||
data, err := os.ReadFile(file)
|
||||
if os.IsNotExist(err) {
|
||||
return map[string]string{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pins := map[string]string{}
|
||||
if err := json.Unmarshal(data, &pins); err != nil {
|
||||
return nil, fmt.Errorf("read pinned SSH fingerprints: %w", err)
|
||||
}
|
||||
return pins, nil
|
||||
}
|
||||
|
||||
func (s *SSH) writePins(pins map[string]string) error {
|
||||
dir := filepath.Join(s.root, "keys")
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := json.MarshalIndent(pins, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.CreateTemp(dir, ".known-hosts-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := file.Name()
|
||||
if _, err := file.Write(data); err != nil {
|
||||
_ = file.Close()
|
||||
_ = os.Remove(name)
|
||||
return err
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
_ = os.Remove(name)
|
||||
return err
|
||||
}
|
||||
return os.Rename(name, filepath.Join(dir, "known_hosts.json"))
|
||||
}
|
||||
|
||||
func confinedPath(home, requested string) (string, error) {
|
||||
requested = strings.TrimSpace(requested)
|
||||
if requested == "" || strings.ContainsRune(requested, '\x00') {
|
||||
return "", errors.New("guest path is required")
|
||||
}
|
||||
home = path.Clean(home)
|
||||
if !path.IsAbs(home) || home == "." {
|
||||
return "", errors.New("guest home directory is unavailable")
|
||||
}
|
||||
var target string
|
||||
if path.IsAbs(requested) {
|
||||
target = path.Clean(requested)
|
||||
} else {
|
||||
target = path.Join(home, requested)
|
||||
}
|
||||
if !withinGuestHome(home, target) {
|
||||
return "", errors.New("guest path must remain inside the guest home directory")
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
func withinGuestHome(home, target string) bool {
|
||||
home = path.Clean(home)
|
||||
target = path.Clean(target)
|
||||
return target == home || strings.HasPrefix(target, strings.TrimSuffix(home, "/")+"/")
|
||||
}
|
||||
|
||||
func mkdirGuestPath(transfer *sftp.Client, home, target string) error {
|
||||
if !withinGuestHome(home, target) {
|
||||
return errors.New("guest directory must remain inside the guest home directory")
|
||||
}
|
||||
relative := strings.TrimPrefix(strings.TrimPrefix(path.Clean(target), path.Clean(home)), "/")
|
||||
current := path.Clean(home)
|
||||
for _, part := range strings.Split(relative, "/") {
|
||||
if part == "." || part == "" {
|
||||
continue
|
||||
}
|
||||
current = path.Join(current, part)
|
||||
info, err := transfer.Lstat(current)
|
||||
if os.IsNotExist(err) {
|
||||
if err := transfer.Mkdir(current); err != nil && !strings.Contains(strings.ToLower(err.Error()), "already exists") {
|
||||
return err
|
||||
}
|
||||
info, err = transfer.Lstat(current)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 || !info.IsDir() {
|
||||
return fmt.Errorf("guest directory component %q is not a normal directory", current)
|
||||
}
|
||||
resolved, err := transfer.RealPath(current)
|
||||
if err != nil || !withinGuestHome(home, resolved) {
|
||||
return errors.New("guest directory resolves outside the guest home directory")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type outputWriter struct {
|
||||
mu sync.Mutex
|
||||
file *os.File
|
||||
count int64
|
||||
head []byte
|
||||
tail []byte
|
||||
}
|
||||
|
||||
func (w *outputWriter) Write(data []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
n, err := w.file.Write(data)
|
||||
if n > 0 {
|
||||
w.count += int64(n)
|
||||
if len(w.head) < 8<<10 {
|
||||
keep := min(8<<10-len(w.head), n)
|
||||
w.head = append(w.head, data[:keep]...)
|
||||
}
|
||||
w.tail = append(w.tail, data[:n]...)
|
||||
if len(w.tail) > 8<<10 {
|
||||
w.tail = append(w.tail[:0], w.tail[len(w.tail)-(8<<10):]...)
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *outputWriter) result() string {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.count <= 16<<10 {
|
||||
overlap := int64(len(w.head)+len(w.tail)) - w.count
|
||||
if overlap > 0 {
|
||||
return string(w.head) + string(w.tail[overlap:])
|
||||
}
|
||||
return string(w.head) + string(w.tail)
|
||||
}
|
||||
return string(w.head) + "\n… output truncated …\n" + string(w.tail)
|
||||
}
|
||||
|
||||
func (w *outputWriter) truncated() bool {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.count > 16<<10
|
||||
}
|
||||
|
||||
func shellCommand(command, cwd string, env map[string]string) string {
|
||||
var b strings.Builder
|
||||
if cwd != "" {
|
||||
fmt.Fprintf(&b, "cd %s && ", shellQuote(cwd))
|
||||
}
|
||||
for key, value := range env {
|
||||
if !safeEnvName(key) {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, "%s=%s ", key, shellQuote(value))
|
||||
}
|
||||
b.WriteString("sh -lc ")
|
||||
b.WriteString(shellQuote(command))
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func safeEnvName(key string) bool {
|
||||
if key == "" || (key[0] != '_' && (key[0] < 'A' || key[0] > 'Z') && (key[0] < 'a' || key[0] > 'z')) {
|
||||
return false
|
||||
}
|
||||
for _, r := range key {
|
||||
if (r < 'A' || r > 'Z') && (r < 'a' || r > 'z') && (r < '0' || r > '9') && r != '_' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" }
|
||||
@@ -0,0 +1,108 @@
|
||||
package guest
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPublicKeyIsPersistentAndValid(t *testing.T) {
|
||||
store := NewSSH(t.TempDir())
|
||||
first, err := store.PublicKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := store.PublicKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first != second || !strings.HasPrefix(first, "ssh-ed25519 ") {
|
||||
t.Fatalf("public key was not stable Ed25519: first=%q second=%q", first, second)
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(store.root, "keys", "id_ed25519"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if runtime.GOOS != "windows" && info.Mode().Perm()&0o077 != 0 {
|
||||
t.Fatalf("private key permissions are too broad: %o", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfinedGuestPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "relative", path: "work/project", want: "/Users/test/work/project"},
|
||||
{name: "absolute inside home", path: "/Users/test/Documents/out.txt", want: "/Users/test/Documents/out.txt"},
|
||||
{name: "traversal", path: "../../Library/secret", wantErr: true},
|
||||
{name: "absolute outside home", path: "/etc/passwd", wantErr: true},
|
||||
{name: "empty", path: "", wantErr: true},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := confinedPath("/Users/test", test.path)
|
||||
if (err != nil) != test.wantErr || got != test.want {
|
||||
t.Fatalf("confinedPath(%q) = %q, %v", test.path, got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputWriterReturnsFullOrHeadAndTail(t *testing.T) {
|
||||
file, err := os.CreateTemp(t.TempDir(), "output-*.log")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file.Close()
|
||||
writer := &outputWriter{file: file}
|
||||
input := strings.Repeat("a", 9<<10) + strings.Repeat("z", 9<<10)
|
||||
if _, err := writer.Write([]byte(input)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := writer.result()
|
||||
if !writer.truncated() || !strings.HasPrefix(output, strings.Repeat("a", 8<<10)) || !strings.HasSuffix(output, strings.Repeat("z", 8<<10)) {
|
||||
t.Fatal("large output did not preserve the first and last 8 KiB")
|
||||
}
|
||||
|
||||
file2, err := os.CreateTemp(t.TempDir(), "small-output-*.log")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer file2.Close()
|
||||
small := &outputWriter{file: file2}
|
||||
if _, err := small.Write([]byte("short output")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := small.result(); got != "short output" || small.truncated() {
|
||||
t.Fatalf("small result = %q, truncated=%v", got, small.truncated())
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLogPages(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
logs := filepath.Join(root, "logs")
|
||||
if err := os.Mkdir(logs, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const logID = "guest-exec-test.log"
|
||||
content := strings.Repeat("x", 10000)
|
||||
if err := os.WriteFile(filepath.Join(logs, logID), []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := NewSSH(root)
|
||||
page, err := store.ReadLog(logID, 8000, 8192)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if page["text"] != strings.Repeat("x", 2000) || page["next_offset"] != int64(10000) || page["eof"] != true {
|
||||
t.Fatalf("unexpected final log page: %+v", page)
|
||||
}
|
||||
if _, err := store.ReadLog("..\\outside", 0, 10); err == nil {
|
||||
t.Fatal("accepted path traversal as a log id")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,742 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/reims-go/reims-agent/internal/guest"
|
||||
)
|
||||
|
||||
const protocolVersion = "2025-06-18"
|
||||
|
||||
type Host interface {
|
||||
Call(context.Context, string, any, any) error
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
host Host
|
||||
mu sync.Mutex
|
||||
guest *guest.SSH
|
||||
}
|
||||
|
||||
type request struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *rpcError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type hostReply struct {
|
||||
Data string `json:"data"`
|
||||
MIMEType string `json:"mime_type"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SourceWidth int `json:"source_width"`
|
||||
SourceHeight int `json:"source_height"`
|
||||
Characters int `json:"characters"`
|
||||
VMs []any `json:"vms"`
|
||||
OK bool `json:"ok"`
|
||||
}
|
||||
|
||||
func New() *Server {
|
||||
root, err := os.Getwd()
|
||||
if err != nil {
|
||||
root = "."
|
||||
}
|
||||
return &Server{guest: guest.NewSSH(filepath.Clean(root))}
|
||||
}
|
||||
|
||||
func (s *Server) BindHost(host Host) { s.host = host }
|
||||
|
||||
func (s *Server) Handle(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) {
|
||||
var req request
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.JSONRPC != "2.0" || strings.TrimSpace(req.Method) == "" {
|
||||
return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: -32600, Message: "invalid JSON-RPC request"}})
|
||||
}
|
||||
if len(req.ID) == 0 || string(req.ID) == "null" {
|
||||
if req.Method == "notifications/initialized" || strings.HasPrefix(req.Method, "notifications/") {
|
||||
return json.RawMessage("null"), nil
|
||||
}
|
||||
return json.RawMessage("null"), nil
|
||||
}
|
||||
if req.Method == "tools/call" || req.Method == "resources/read" {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
}
|
||||
result, err := s.dispatch(ctx, req.Method, req.Params)
|
||||
if err != nil {
|
||||
code := -32000
|
||||
if errors.Is(err, errUnknownMethod) {
|
||||
code = -32601
|
||||
}
|
||||
if errors.Is(err, errInvalidParams) {
|
||||
code = -32602
|
||||
}
|
||||
return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: code, Message: err.Error()}})
|
||||
}
|
||||
return marshal(response{JSONRPC: "2.0", ID: req.ID, Result: result})
|
||||
}
|
||||
|
||||
var (
|
||||
errUnknownMethod = errors.New("unknown MCP method")
|
||||
errInvalidParams = errors.New("invalid MCP parameters")
|
||||
)
|
||||
|
||||
func (s *Server) dispatch(ctx context.Context, method string, raw json.RawMessage) (any, error) {
|
||||
switch method {
|
||||
case "initialize":
|
||||
return map[string]any{
|
||||
"protocolVersion": protocolVersion,
|
||||
"capabilities": map[string]any{"tools": map[string]any{"listChanged": false}, "resources": map[string]any{"subscribe": false, "listChanged": false}},
|
||||
"serverInfo": map[string]any{"name": "reims-agent", "version": "0.1.0"},
|
||||
}, nil
|
||||
case "ping":
|
||||
return map[string]any{}, nil
|
||||
case "tools/list":
|
||||
return map[string]any{"tools": toolCatalog}, nil
|
||||
case "resources/list":
|
||||
return s.listResources(ctx)
|
||||
case "tools/call":
|
||||
return s.callTool(ctx, raw)
|
||||
case "resources/read":
|
||||
return s.readResource(ctx, raw)
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: %s", errUnknownMethod, method)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &req); err != nil || strings.TrimSpace(req.Name) == "" {
|
||||
return nil, fmt.Errorf("%w: tool name is required", errInvalidParams)
|
||||
}
|
||||
if s.host == nil {
|
||||
return toolError("Reims-Go host is unavailable"), nil
|
||||
}
|
||||
result, err := s.invoke(ctx, req.Name, req.Arguments)
|
||||
if err != nil {
|
||||
return toolError(err.Error()), nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func toolError(message string) map[string]any {
|
||||
return map[string]any{"isError": true, "content": []any{map[string]any{"type": "text", "text": message}}}
|
||||
}
|
||||
|
||||
func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) (any, error) {
|
||||
switch name {
|
||||
case "vm_list":
|
||||
var out hostReply
|
||||
if err := s.host.Call(ctx, "host/vm.list", nil, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(out.VMs), nil
|
||||
case "vm_get":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out map[string]any
|
||||
if err := s.host.Call(ctx, "host/vm.get", args, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(out), nil
|
||||
case "vm_start", "vm_shutdown":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
method := "host/vm.start"
|
||||
if name == "vm_shutdown" {
|
||||
method = "host/vm.shutdown"
|
||||
}
|
||||
var out hostReply
|
||||
if err := s.host.Call(ctx, method, args, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
case "vm_unlock":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if args.VM == "" {
|
||||
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
||||
}
|
||||
var typed hostReply
|
||||
if err := s.host.Call(ctx, "host/console.typeSecret", map[string]any{"vm": args.VM, "setting": "login_password"}, &typed); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var key hostReply
|
||||
if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": "ret"}, &key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var screen hostReply
|
||||
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"content": []any{
|
||||
map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType},
|
||||
map[string]any{"type": "text", "text": "Login password entered. Current screen attached."},
|
||||
}}, nil
|
||||
case "computer":
|
||||
return s.computer(ctx, raw)
|
||||
case "wait_for_screen":
|
||||
return s.waitForScreen(ctx, raw)
|
||||
case "guest_public_key":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if args.VM == "" {
|
||||
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
||||
}
|
||||
key, err := s.guest.PublicKey()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"public_key": strings.TrimSpace(key), "instructions": "Add this key as one line in the guest account's ~/.ssh/authorized_keys. The private key remains in the plugin data directory."}), nil
|
||||
case "guest_wait_ready":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
address, username, err := s.guestAddress(ctx, args.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if args.TimeoutMS == 0 {
|
||||
args.TimeoutMS = 10000
|
||||
}
|
||||
if args.TimeoutMS < 1 || args.TimeoutMS > 30000 {
|
||||
return nil, fmt.Errorf("%w: timeout_ms must be between 1 and 30000", errInvalidParams)
|
||||
}
|
||||
result, err := s.guest.WaitReady(ctx, args.VM, address, username, time.Duration(args.TimeoutMS)*time.Millisecond)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result["trust_required"] == true {
|
||||
publicKey, keyErr := s.guest.PublicKey()
|
||||
if keyErr != nil {
|
||||
return nil, keyErr
|
||||
}
|
||||
result["plugin_public_key"] = strings.TrimSpace(publicKey)
|
||||
}
|
||||
return textResult(result), nil
|
||||
case "guest_trust_host":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
address, _, err := s.guestAddress(ctx, args.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if args.Fingerprint == "" {
|
||||
return nil, fmt.Errorf("%w: fingerprint is required", errInvalidParams)
|
||||
}
|
||||
if err := s.guest.TrustHostKeyContext(ctx, args.VM, address, args.Fingerprint); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"trusted": true, "fingerprint": args.Fingerprint}), nil
|
||||
case "guest_exec":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
Command string `json:"command"`
|
||||
CWD string `json:"cwd"`
|
||||
Env map[string]string `json:"env"`
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
address, username, err := s.guestAddress(ctx, args.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if args.TimeoutMS == 0 {
|
||||
args.TimeoutMS = 900000
|
||||
}
|
||||
result, err := s.guest.Exec(ctx, args.VM, address, username, args.Command, args.CWD, args.Env, time.Duration(args.TimeoutMS)*time.Millisecond)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(result), nil
|
||||
case "guest_put":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
LocalPath string `json:"local_path"`
|
||||
RemotePath string `json:"remote_path"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
address, username, err := s.guestAddress(ctx, args.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := s.guest.Put(ctx, args.VM, address, username, args.LocalPath, args.RemotePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(result), nil
|
||||
case "guest_get":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
RemotePath string `json:"remote_path"`
|
||||
LocalPath string `json:"local_path"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
address, username, err := s.guestAddress(ctx, args.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := s.guest.Get(ctx, args.VM, address, username, args.RemotePath, args.LocalPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(result), nil
|
||||
case "guest_logs":
|
||||
var args struct {
|
||||
LogID string `json:"log_id"`
|
||||
Offset int64 `json:"offset"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := s.guest.ReadLog(args.LogID, args.Offset, args.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(result), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown tool %q", name)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) guestAddress(ctx context.Context, ref string) (string, string, error) {
|
||||
if strings.TrimSpace(ref) == "" {
|
||||
return "", "", fmt.Errorf("%w: vm is required", errInvalidParams)
|
||||
}
|
||||
var vm map[string]any
|
||||
if err := s.host.Call(ctx, "host/vm.get", map[string]string{"vm": ref}, &vm); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
portValue, ok := vm["ssh_port"].(float64)
|
||||
if !ok || portValue < 1 || portValue > 65535 {
|
||||
return "", "", errors.New("ssh_unavailable: SSH port forwarding is not enabled for this VM")
|
||||
}
|
||||
username, _ := vm["ssh_username"].(string)
|
||||
return net.JoinHostPort("127.0.0.1", fmt.Sprint(int(portValue))), username, nil
|
||||
}
|
||||
|
||||
func (s *Server) computer(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
Action string `json:"action"`
|
||||
X int `json:"x"`
|
||||
Y int `json:"y"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Button string `json:"button"`
|
||||
Text string `json:"text"`
|
||||
Key string `json:"key"`
|
||||
Modifiers []string `json:"modifiers"`
|
||||
X2 int `json:"x2"`
|
||||
Y2 int `json:"y2"`
|
||||
Delta int `json:"delta"`
|
||||
Horizontal bool `json:"horizontal"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if args.VM == "" {
|
||||
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
||||
}
|
||||
action := strings.ToLower(strings.TrimSpace(args.Action))
|
||||
if action == "screenshot" {
|
||||
var screen hostReply
|
||||
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{
|
||||
"content": []any{
|
||||
map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType},
|
||||
map[string]any{"type": "text", "text": fmt.Sprintf("Screen %dx%d, framebuffer %dx%d", screen.Width, screen.Height, screen.SourceWidth, screen.SourceHeight)},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
if action == "zoom" {
|
||||
var screen hostReply
|
||||
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cropped, width, height, err := cropJPEG(screen.Data, args.X, args.Y, args.Width, args.Height)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"content": []any{map[string]any{"type": "image", "data": cropped, "mimeType": "image/jpeg"}, map[string]any{"type": "text", "text": fmt.Sprintf("Crop %dx%d", width, height)}}}, nil
|
||||
}
|
||||
if action == "type" {
|
||||
var out hostReply
|
||||
if err := s.host.Call(ctx, "host/console.type", map[string]any{"vm": args.VM, "text": args.Text}, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"characters": out.Characters}), nil
|
||||
}
|
||||
if action == "key" {
|
||||
var out hostReply
|
||||
if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": args.Key, "modifiers": args.Modifiers}, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
}
|
||||
if action == "wait" {
|
||||
timeout := time.Duration(args.Delta) * time.Millisecond
|
||||
if timeout < 0 || timeout > 30*time.Second {
|
||||
return nil, fmt.Errorf("%w: wait delta must be between 0 and 30000 milliseconds", errInvalidParams)
|
||||
}
|
||||
timer := time.NewTimer(timeout)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return textResult(map[string]any{"waited_ms": timeout.Milliseconds()}), nil
|
||||
}
|
||||
|
||||
button := "left"
|
||||
buttonActions := map[string]string{"left_click": "left", "right_click": "right", "middle_click": "middle", "double_click": "left"}
|
||||
if mapped, ok := buttonActions[action]; ok {
|
||||
button = mapped
|
||||
if err := s.movePointer(ctx, args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clicks := 1
|
||||
if action == "double_click" {
|
||||
clicks = 2
|
||||
}
|
||||
for range clicks {
|
||||
var out hostReply
|
||||
if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "click", "button": button}, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
}
|
||||
if action == "mouse_move" {
|
||||
if err := s.movePointer(ctx, args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
}
|
||||
if action == "left_click_drag" {
|
||||
if err := s.movePointer(ctx, args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out hostReply
|
||||
if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "button", "button": "left", "down": true}, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args.X, args.Y = args.X2, args.Y2
|
||||
if err := s.movePointer(ctx, args); err != nil {
|
||||
_ = s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "button", "button": "left", "down": false}, &out)
|
||||
return nil, err
|
||||
}
|
||||
if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "button", "button": "left", "down": false}, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
}
|
||||
if action == "scroll" {
|
||||
if err := s.movePointer(ctx, args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out hostReply
|
||||
if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "scroll", "delta": args.Delta, "horizontal": args.Horizontal}, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
}
|
||||
return nil, fmt.Errorf("unknown computer action %q", action)
|
||||
}
|
||||
|
||||
func (s *Server) movePointer(ctx context.Context, args struct {
|
||||
VM string `json:"vm"`
|
||||
Action string `json:"action"`
|
||||
X int `json:"x"`
|
||||
Y int `json:"y"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
Button string `json:"button"`
|
||||
Text string `json:"text"`
|
||||
Key string `json:"key"`
|
||||
Modifiers []string `json:"modifiers"`
|
||||
X2 int `json:"x2"`
|
||||
Y2 int `json:"y2"`
|
||||
Delta int `json:"delta"`
|
||||
Horizontal bool `json:"horizontal"`
|
||||
}) error {
|
||||
if args.Width <= 0 || args.Height <= 0 {
|
||||
var screen hostReply
|
||||
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
||||
return err
|
||||
}
|
||||
args.Width, args.Height = screen.Width, screen.Height
|
||||
}
|
||||
var out hostReply
|
||||
return s.host.Call(ctx, "host/console.pointer", map[string]any{
|
||||
"vm": args.VM, "action": "move", "x": args.X, "y": args.Y, "width": args.Width, "height": args.Height,
|
||||
}, &out)
|
||||
}
|
||||
|
||||
func (s *Server) waitForScreen(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
Baseline string `json:"baseline_sha256"`
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
StableMS int `json:"stable_ms"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if args.VM == "" {
|
||||
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
||||
}
|
||||
if args.TimeoutMS <= 0 {
|
||||
args.TimeoutMS = 10000
|
||||
}
|
||||
if args.TimeoutMS > 30000 || args.StableMS < 0 || args.StableMS > args.TimeoutMS {
|
||||
return nil, fmt.Errorf("%w: timeout must be <= 30000 ms and stable_ms <= timeout_ms", errInvalidParams)
|
||||
}
|
||||
deadline := time.NewTimer(time.Duration(args.TimeoutMS) * time.Millisecond)
|
||||
defer deadline.Stop()
|
||||
var previous string
|
||||
stableSince := time.Time{}
|
||||
for {
|
||||
var screen hostReply
|
||||
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
digest := sha256.Sum256([]byte(screen.Data))
|
||||
current := hex.EncodeToString(digest[:])
|
||||
if current != previous {
|
||||
previous = current
|
||||
stableSince = time.Now()
|
||||
}
|
||||
changed := args.Baseline == "" || current != args.Baseline
|
||||
stable := args.StableMS == 0 || time.Since(stableSince) >= time.Duration(args.StableMS)*time.Millisecond
|
||||
if changed && stable {
|
||||
return map[string]any{"content": []any{
|
||||
map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType},
|
||||
map[string]any{"type": "text", "text": fmt.Sprintf("Screen changed or stable. sha256=%s", current)},
|
||||
}}, nil
|
||||
}
|
||||
timer := time.NewTimer(250 * time.Millisecond)
|
||||
select {
|
||||
case <-timer.C:
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return nil, ctx.Err()
|
||||
case <-deadline.C:
|
||||
timer.Stop()
|
||||
return toolTimeout(current), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func toolTimeout(lastHash string) map[string]any {
|
||||
return map[string]any{"isError": true, "content": []any{map[string]any{"type": "text", "text": "Timed out waiting for a screen change. Last frame sha256=" + lastHash}}}
|
||||
}
|
||||
|
||||
func (s *Server) readResource(ctx context.Context, raw json.RawMessage) (any, error) {
|
||||
var args struct {
|
||||
URI string `json:"uri"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.HasPrefix(args.URI, "reims://vm/") && strings.HasSuffix(args.URI, "/screen") {
|
||||
vm := strings.TrimSuffix(strings.TrimPrefix(args.URI, "reims://vm/"), "/screen")
|
||||
vm, err := url.PathUnescape(vm)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid VM resource URI: %w", err)
|
||||
}
|
||||
var screen hostReply
|
||||
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": vm}, &screen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"contents": []any{map[string]any{"uri": args.URI, "mimeType": screen.MIMEType, "blob": screen.Data}}}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unknown MCP resource %q", args.URI)
|
||||
}
|
||||
|
||||
func (s *Server) listResources(ctx context.Context) (any, error) {
|
||||
if s.host == nil {
|
||||
return map[string]any{"resources": []any{}}, nil
|
||||
}
|
||||
var result hostReply
|
||||
if err := s.host.Call(ctx, "host/vm.list", nil, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resources := make([]any, 0, len(result.VMs))
|
||||
for _, item := range result.VMs {
|
||||
vm, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ref, _ := vm["vm"].(string)
|
||||
name, _ := vm["name"].(string)
|
||||
if ref == "" {
|
||||
continue
|
||||
}
|
||||
resources = append(resources, map[string]any{
|
||||
"uri": "reims://vm/" + url.PathEscape(ref) + "/screen",
|
||||
"name": name + " screen",
|
||||
"mimeType": "image/jpeg",
|
||||
})
|
||||
}
|
||||
return map[string]any{"resources": resources}, nil
|
||||
}
|
||||
|
||||
func cropJPEG(encoded string, x, y, width, height int) (string, int, int, error) {
|
||||
if width <= 0 || height <= 0 || width > 2048 || height > 2048 {
|
||||
return "", 0, 0, fmt.Errorf("crop width and height must be between 1 and 2048 pixels")
|
||||
}
|
||||
data, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return "", 0, 0, err
|
||||
}
|
||||
img, err := jpeg.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", 0, 0, err
|
||||
}
|
||||
bounds := img.Bounds()
|
||||
area := image.Rect(x, y, x+width, y+height).Intersect(bounds)
|
||||
if area.Empty() {
|
||||
return "", 0, 0, errors.New("crop rectangle does not intersect the screen")
|
||||
}
|
||||
var cropped image.Image
|
||||
if sub, ok := img.(interface {
|
||||
SubImage(image.Rectangle) image.Image
|
||||
}); ok {
|
||||
cropped = sub.SubImage(area)
|
||||
} else {
|
||||
return "", 0, 0, errors.New("screen image cannot be cropped")
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, cropped, &jpeg.Options{Quality: 84}); err != nil {
|
||||
return "", 0, 0, err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes()), area.Dx(), area.Dy(), nil
|
||||
}
|
||||
|
||||
func decodeArguments(raw json.RawMessage, target any) error {
|
||||
if len(raw) == 0 {
|
||||
raw = json.RawMessage(`{}`)
|
||||
}
|
||||
if err := json.Unmarshal(raw, target); err != nil {
|
||||
return fmt.Errorf("%w: %v", errInvalidParams, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func textResult(value any) map[string]any {
|
||||
encoded, err := json.MarshalIndent(value, "", " ")
|
||||
if err != nil {
|
||||
return toolError(err.Error())
|
||||
}
|
||||
return map[string]any{"content": []any{map[string]any{"type": "text", "text": string(encoded)}}}
|
||||
}
|
||||
|
||||
func marshal(value any) (json.RawMessage, error) {
|
||||
encoded, err := json.Marshal(value)
|
||||
return json.RawMessage(encoded), err
|
||||
}
|
||||
|
||||
var toolCatalog = []map[string]any{
|
||||
{"name": "vm_list", "description": "List virtual machines visible to Reims-Go.", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{}, "additionalProperties": false}},
|
||||
{"name": "vm_get", "description": "Read the state and capabilities of one virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "vm_start", "description": "Start a virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "vm_shutdown", "description": "Request a normal guest shutdown.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "vm_unlock", "description": "Enter the host-stored macOS login password and return the current screen.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "computer", "description": "Capture or interact with a virtual machine display.", "inputSchema": objectSchema(map[string]any{
|
||||
"vm": map[string]any{"type": "string"},
|
||||
"action": map[string]any{"type": "string", "enum": []string{"screenshot", "left_click", "right_click", "middle_click", "double_click", "mouse_move", "left_click_drag", "scroll", "key", "type", "wait", "zoom"}},
|
||||
"x": map[string]any{"type": "integer"}, "y": map[string]any{"type": "integer"},
|
||||
"width": map[string]any{"type": "integer"}, "height": map[string]any{"type": "integer"},
|
||||
"button": map[string]any{"type": "string", "enum": []string{"left", "right", "middle"}},
|
||||
"text": map[string]any{"type": "string"}, "key": map[string]any{"type": "string"},
|
||||
"modifiers": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
|
||||
"x2": map[string]any{"type": "integer"}, "y2": map[string]any{"type": "integer"},
|
||||
"delta": map[string]any{"type": "integer"}, "horizontal": map[string]any{"type": "boolean"},
|
||||
}, []string{"vm", "action"})},
|
||||
{"name": "wait_for_screen", "description": "Wait for a virtual machine screen frame to change or remain stable.", "inputSchema": objectSchema(map[string]any{
|
||||
"vm": map[string]any{"type": "string"}, "baseline_sha256": map[string]any{"type": "string"},
|
||||
"timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000},
|
||||
"stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000},
|
||||
}, []string{"vm"})},
|
||||
{"name": "guest_public_key", "description": "Create or return this plugin's SSH public key for explicit guest-side installation.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "guest_wait_ready", "description": "Wait for guest SSH and report a host fingerprint that must be reviewed before trust.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000}}, []string{"vm"})},
|
||||
{"name": "guest_trust_host", "description": "Pin an SSH host fingerprint after verifying it against the live guest connection.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "fingerprint": map[string]any{"type": "string"}}, []string{"vm", "fingerprint"})},
|
||||
{"name": "guest_exec", "description": "Run a command over pinned SSH and return its exit code, bounded output, and a paginatable log id.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "command": map[string]any{"type": "string"}, "cwd": map[string]any{"type": "string"}, "env": map[string]any{"type": "object", "additionalProperties": map[string]any{"type": "string"}}, "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 1800000}}, []string{"vm", "command"})},
|
||||
{"name": "guest_put", "description": "Upload one file over SFTP to a path inside the guest user's home directory.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "local_path": map[string]any{"type": "string"}, "remote_path": map[string]any{"type": "string"}}, []string{"vm", "local_path", "remote_path"})},
|
||||
{"name": "guest_get", "description": "Download one file over SFTP from inside the guest user's home directory.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "remote_path": map[string]any{"type": "string"}, "local_path": map[string]any{"type": "string"}}, []string{"vm", "remote_path", "local_path"})},
|
||||
{"name": "guest_logs", "description": "Read a bounded page from the complete output file of a previous guest_exec call.", "inputSchema": objectSchema(map[string]any{"log_id": map[string]any{"type": "string"}, "offset": map[string]any{"type": "integer", "minimum": 0}, "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 65536}}, []string{"log_id"})},
|
||||
}
|
||||
|
||||
func objectSchema(properties map[string]any, required []string) map[string]any {
|
||||
return map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/reims-go/reims-agent/internal/guest"
|
||||
)
|
||||
|
||||
type hostCall struct {
|
||||
method string
|
||||
params any
|
||||
}
|
||||
|
||||
type testHost struct {
|
||||
calls []hostCall
|
||||
frames []string
|
||||
frameIndex int
|
||||
secretValue string
|
||||
}
|
||||
|
||||
func (h *testHost) Call(_ context.Context, method string, params any, out any) error {
|
||||
h.calls = append(h.calls, hostCall{method: method, params: params})
|
||||
if strings.HasSuffix(method, "screenshot") {
|
||||
frame := h.frames[0]
|
||||
if h.frameIndex < len(h.frames) {
|
||||
frame = h.frames[h.frameIndex]
|
||||
h.frameIndex++
|
||||
}
|
||||
*out.(*hostReply) = hostReply{
|
||||
Data: frame, MIMEType: "image/jpeg", Width: 2, Height: 2, SourceWidth: 2, SourceHeight: 2,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(method, "typeSecret") {
|
||||
*out.(*hostReply) = hostReply{Characters: 19}
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(method, "vm.get") {
|
||||
*out.(*map[string]any) = map[string]any{"vm": "driver:macos1", "name": "macos1", "state": "running"}
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(method, "vm.list") {
|
||||
*out.(*hostReply) = hostReply{VMs: []any{map[string]any{"vm": "driver:macos1", "name": "macos1"}}}
|
||||
return nil
|
||||
}
|
||||
if result, ok := out.(*hostReply); ok {
|
||||
*result = hostReply{OK: true}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestMCPInitializeAndVMGet(t *testing.T) {
|
||||
host := &testHost{}
|
||||
server := New()
|
||||
server.BindHost(host)
|
||||
initialized := sendRequest(t, server, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`)
|
||||
if !strings.Contains(string(initialized), protocolVersion) {
|
||||
t.Fatalf("initialize response missing protocol version: %s", initialized)
|
||||
}
|
||||
response := sendRequest(t, server, `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"vm_get","arguments":{"vm":"macos1"}}}`)
|
||||
content := parseResponse(t, response)["result"].(map[string]any)["content"].([]any)
|
||||
if !strings.Contains(content[0].(map[string]any)["text"].(string), `"name": "macos1"`) {
|
||||
t.Fatalf("vm_get response missing VM detail: %s", response)
|
||||
}
|
||||
if len(host.calls) != 1 || host.calls[0].method != "host/vm.get" {
|
||||
t.Fatalf("VM call route = %+v", host.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestToolsAreAdvertisedAndPublicKeyIsAvailable(t *testing.T) {
|
||||
server := New()
|
||||
server.guest = guest.NewSSH(t.TempDir())
|
||||
server.BindHost(&testHost{})
|
||||
response := sendRequest(t, server, `{"jsonrpc":"2.0","id":7,"method":"tools/list","params":{}}`)
|
||||
encoded, err := json.Marshal(parseResponse(t, response)["result"].(map[string]any)["tools"])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"guest_public_key", "guest_wait_ready", "guest_trust_host", "guest_exec", "guest_put", "guest_get", "guest_logs"} {
|
||||
if !strings.Contains(string(encoded), `"name":"`+name+`"`) {
|
||||
t.Errorf("MCP tool list is missing %s", name)
|
||||
}
|
||||
}
|
||||
key := sendRequest(t, server, `{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"guest_public_key","arguments":{"vm":"macos1"}}}`)
|
||||
content := parseResponse(t, key)["result"].(map[string]any)["content"].([]any)
|
||||
text := content[0].(map[string]any)["text"].(string)
|
||||
if !strings.Contains(text, "ssh-ed25519 ") || strings.Contains(text, "PRIVATE KEY") {
|
||||
t.Fatalf("guest public key response is invalid or exposes private material: %s", key)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScreenshotAndZoomReturnImages(t *testing.T) {
|
||||
frame := base64JPEG(t, color.RGBA{R: 180, A: 255})
|
||||
host := &testHost{frames: []string{frame}}
|
||||
server := New()
|
||||
server.BindHost(host)
|
||||
shot := sendRequest(t, server, `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"screenshot"}}}`)
|
||||
shotContent := parseResponse(t, shot)["result"].(map[string]any)["content"].([]any)
|
||||
if shotContent[0].(map[string]any)["type"] != "image" || shotContent[0].(map[string]any)["mimeType"] != "image/jpeg" {
|
||||
t.Fatalf("screenshot result missing image content: %s", shot)
|
||||
}
|
||||
zoom := sendRequest(t, server, `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"zoom","x":0,"y":0,"width":1,"height":1}}}`)
|
||||
zoomContent := parseResponse(t, zoom)["result"].(map[string]any)["content"].([]any)
|
||||
if zoomContent[0].(map[string]any)["type"] != "image" || zoomContent[1].(map[string]any)["text"] != "Crop 1x1" {
|
||||
t.Fatalf("zoom result missing cropped image: %s", zoom)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVMUnlockNeverReturnsThePassword(t *testing.T) {
|
||||
const password = "mcp-password-fixture"
|
||||
host := &testHost{frames: []string{base64JPEG(t, color.RGBA{G: 120, A: 255})}, secretValue: password}
|
||||
server := New()
|
||||
server.BindHost(host)
|
||||
response := sendRequest(t, server, `{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"vm_unlock","arguments":{"vm":"macos1"}}}`)
|
||||
if strings.Contains(string(response), password) {
|
||||
t.Fatalf("vm_unlock leaked password in MCP response: %s", response)
|
||||
}
|
||||
if len(host.calls) != 3 {
|
||||
t.Fatalf("vm_unlock host calls = %d, want typeSecret, key and screenshot", len(host.calls))
|
||||
}
|
||||
var secretParams map[string]any
|
||||
encoded, _ := json.Marshal(host.calls[0].params)
|
||||
_ = json.Unmarshal(encoded, &secretParams)
|
||||
if host.calls[0].method != "host/console.typeSecret" || secretParams["setting"] != "login_password" {
|
||||
t.Fatalf("vm_unlock sent unexpected secret call: %+v", host.calls[0])
|
||||
}
|
||||
if strings.Contains(string(encoded), password) {
|
||||
t.Fatal("vm_unlock sent password to the host as a plaintext argument")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForScreenRecognizesChangedFrame(t *testing.T) {
|
||||
first := base64JPEG(t, color.RGBA{B: 200, A: 255})
|
||||
second := base64JPEG(t, color.RGBA{R: 200, A: 255})
|
||||
baseline := sha256.Sum256([]byte(first))
|
||||
host := &testHost{frames: []string{first, second}}
|
||||
server := New()
|
||||
server.BindHost(host)
|
||||
payload := `{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","baseline_sha256":"` + hex.EncodeToString(baseline[:]) + `","timeout_ms":3000}}}`
|
||||
response := sendRequest(t, server, payload)
|
||||
content := parseResponse(t, response)["result"].(map[string]any)["content"].([]any)
|
||||
if content[0].(map[string]any)["type"] != "image" || host.frameIndex < 2 {
|
||||
t.Fatalf("wait_for_screen did not observe a changed frame: response=%s calls=%d", response, host.frameIndex)
|
||||
}
|
||||
}
|
||||
|
||||
func parseResponse(t *testing.T, raw json.RawMessage) map[string]any {
|
||||
t.Helper()
|
||||
var response map[string]any
|
||||
if err := json.Unmarshal(raw, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func sendRequest(t *testing.T, server *Server, raw string) json.RawMessage {
|
||||
t.Helper()
|
||||
result, err := server.Handle(context.Background(), json.RawMessage(raw))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func base64JPEG(t *testing.T, fill color.Color) string {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, 2, 2))
|
||||
for y := range 2 {
|
||||
for x := range 2 {
|
||||
img.Set(x, y, fill)
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 100}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(buf.Bytes())
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package sidecar
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
const maxFrameBytes = 8 << 20
|
||||
|
||||
type MCPHandler interface {
|
||||
Handle(context.Context, json.RawMessage) (json.RawMessage, error)
|
||||
}
|
||||
|
||||
type HostClient struct{ Server *Server }
|
||||
|
||||
func (c HostClient) Call(ctx context.Context, method string, params any, out any) error {
|
||||
if c.Server == nil {
|
||||
return errors.New("Reims-Go Host API is unavailable")
|
||||
}
|
||||
return c.Server.CallHost(ctx, method, params, out)
|
||||
}
|
||||
|
||||
type envelope struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Params json.RawMessage `json:"params,omitempty"`
|
||||
Result json.RawMessage `json:"result,omitempty"`
|
||||
Error *rpcError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type rpcError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type hostReply struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
in *bufio.Reader
|
||||
out io.Writer
|
||||
mcp MCPHandler
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]chan envelope
|
||||
writeMu sync.Mutex
|
||||
nextID atomic.Uint64
|
||||
}
|
||||
|
||||
func New(handler MCPHandler) *Server {
|
||||
return &Server{
|
||||
in: bufio.NewReaderSize(os.Stdin, 64*1024),
|
||||
out: os.Stdout,
|
||||
mcp: handler,
|
||||
pending: make(map[string]chan envelope),
|
||||
}
|
||||
}
|
||||
|
||||
func NewWithIO(r io.Reader, w io.Writer, handler MCPHandler) *Server {
|
||||
return &Server{
|
||||
in: bufio.NewReaderSize(r, 64*1024),
|
||||
out: w,
|
||||
mcp: handler,
|
||||
pending: make(map[string]chan envelope),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Serve(parent context.Context) error {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
defer cancel()
|
||||
for {
|
||||
frame, err := readFrame(s.in)
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
var env envelope
|
||||
if err := json.Unmarshal(frame, &env); err != nil {
|
||||
continue
|
||||
}
|
||||
if env.Method == "plugin/shutdown" {
|
||||
return nil
|
||||
}
|
||||
if env.Method != "" {
|
||||
go s.dispatch(ctx, env)
|
||||
continue
|
||||
}
|
||||
if len(env.ID) > 0 {
|
||||
key := strings.TrimSpace(string(env.ID))
|
||||
s.mu.Lock()
|
||||
waiter := s.pending[key]
|
||||
s.mu.Unlock()
|
||||
if waiter != nil {
|
||||
select {
|
||||
case waiter <- env:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) dispatch(ctx context.Context, env envelope) {
|
||||
var result any
|
||||
var err error
|
||||
switch env.Method {
|
||||
case "plugin/initialize":
|
||||
result = map[string]any{
|
||||
"pluginApi": "1.1.0",
|
||||
"capabilities": map[string]any{"channels": []string{"mcp"}},
|
||||
}
|
||||
case "plugin/localeChanged":
|
||||
return
|
||||
case "channel/mcp/message":
|
||||
var params struct {
|
||||
Message json.RawMessage `json:"message"`
|
||||
}
|
||||
if err = json.Unmarshal(env.Params, ¶ms); err == nil && len(params.Message) == 0 {
|
||||
err = errors.New("channel message is missing")
|
||||
}
|
||||
if err == nil {
|
||||
var message json.RawMessage
|
||||
message, err = s.mcp.Handle(ctx, params.Message)
|
||||
if err == nil {
|
||||
if len(message) == 0 {
|
||||
message = json.RawMessage("null")
|
||||
}
|
||||
result = map[string]json.RawMessage{"message": message}
|
||||
}
|
||||
}
|
||||
default:
|
||||
err = fmt.Errorf("method not found: %s", env.Method)
|
||||
}
|
||||
if len(env.ID) == 0 {
|
||||
return
|
||||
}
|
||||
response := envelope{JSONRPC: "2.0", ID: env.ID}
|
||||
if err != nil {
|
||||
response.Error = &rpcError{Code: -32000, Message: err.Error()}
|
||||
} else if result == nil {
|
||||
response.Result = json.RawMessage("null")
|
||||
} else {
|
||||
response.Result, _ = json.Marshal(result)
|
||||
}
|
||||
_ = s.writeFrame(response)
|
||||
}
|
||||
|
||||
func (s *Server) CallHost(ctx context.Context, method string, params any, out any) error {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
id := strconv.FormatUint(s.nextID.Add(1), 10)
|
||||
var rawParams json.RawMessage
|
||||
if params != nil {
|
||||
encoded, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rawParams = encoded
|
||||
}
|
||||
waiter := make(chan envelope, 1)
|
||||
s.mu.Lock()
|
||||
s.pending[id] = waiter
|
||||
s.mu.Unlock()
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
delete(s.pending, id)
|
||||
s.mu.Unlock()
|
||||
}()
|
||||
if err := s.writeFrame(envelope{
|
||||
JSONRPC: "2.0",
|
||||
ID: json.RawMessage(id),
|
||||
Method: method,
|
||||
Params: rawParams,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case response := <-waiter:
|
||||
if response.Error != nil {
|
||||
return errors.New(response.Error.Message)
|
||||
}
|
||||
if out != nil && len(response.Result) > 0 && string(response.Result) != "null" {
|
||||
return json.Unmarshal(response.Result, out)
|
||||
}
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) writeFrame(env envelope) error {
|
||||
frame, err := json.Marshal(env)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(frame) > maxFrameBytes {
|
||||
return errors.New("Sidecar RPC frame exceeds limit")
|
||||
}
|
||||
s.writeMu.Lock()
|
||||
defer s.writeMu.Unlock()
|
||||
if _, err := fmt.Fprintf(s.out, "Content-Length: %d\r\n\r\n", len(frame)); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.out.Write(frame)
|
||||
return err
|
||||
}
|
||||
|
||||
func readFrame(reader *bufio.Reader) ([]byte, error) {
|
||||
contentLength := -1
|
||||
for range 64 {
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
break
|
||||
}
|
||||
key, value, ok := strings.Cut(line, ":")
|
||||
if ok && strings.EqualFold(strings.TrimSpace(key), "Content-Length") {
|
||||
length, err := strconv.Atoi(strings.TrimSpace(value))
|
||||
if err != nil || length < 0 || length > maxFrameBytes {
|
||||
return nil, errors.New("invalid Sidecar RPC Content-Length")
|
||||
}
|
||||
contentLength = length
|
||||
}
|
||||
}
|
||||
if contentLength < 0 {
|
||||
return nil, errors.New("Sidecar RPC frame is missing Content-Length")
|
||||
}
|
||||
frame := make([]byte, contentLength)
|
||||
if _, err := io.ReadFull(reader, frame); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return frame, nil
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"schema": 1,
|
||||
"id": "reims.agent",
|
||||
"version": "0.1.0",
|
||||
"name": {
|
||||
"zh-CN": "MCP服务",
|
||||
"en-US": "MCP Service"
|
||||
},
|
||||
"description": {
|
||||
"zh-CN": "通过宿主授权的控制通道向 MCP 客户端提供虚拟机交互工具",
|
||||
"en-US": "Provides VM interaction tools to MCP clients through host-authorized channels"
|
||||
},
|
||||
"publisher": "Reims-Go",
|
||||
"license": "Apache-2.0",
|
||||
"homepage": "https://github.com/reims-go/reims-agent",
|
||||
"engines": {
|
||||
"pluginApi": "^1.1.0"
|
||||
},
|
||||
"platforms": ["windows-x64"],
|
||||
"entry": {
|
||||
"sidecar": "bin/reims-agent.exe"
|
||||
},
|
||||
"settings": {
|
||||
"title": { "zh-CN": "MCP服务", "en-US": "MCP Service" },
|
||||
"x-scope": "vm",
|
||||
"x-group": "collaboration",
|
||||
"x-order": ["username", "login_password"],
|
||||
"properties": {
|
||||
"username": {
|
||||
"type": "string",
|
||||
"title": { "zh-CN": "macOS 用户名", "en-US": "macOS username" },
|
||||
"x-scope": "vm",
|
||||
"x-group": "collaboration"
|
||||
},
|
||||
"login_password": {
|
||||
"type": "string",
|
||||
"title": { "zh-CN": "macOS 登录密码", "en-US": "macOS login password" },
|
||||
"x-secret": true,
|
||||
"x-scope": "vm",
|
||||
"x-group": "collaboration"
|
||||
}
|
||||
}
|
||||
},
|
||||
"contributes": {
|
||||
"channels": [
|
||||
{ "id": "mcp", "framing": "jsonl" }
|
||||
]
|
||||
},
|
||||
"permissions": [
|
||||
"vm:read",
|
||||
"vm:control",
|
||||
"vm:screen",
|
||||
"qmp:write"
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user