├── .github
└── workflows
│ └── release-and-docker.yml
├── .gitignore
├── Dockerfile
├── LICENSE
├── Makefile
├── README.md
├── docs
└── README.zh-Hans.md
├── go.mod
├── go.sum
├── main.go
├── operations
├── app
│ ├── install_mysql.go
│ ├── install_openresty.go
│ └── list_install.go
├── database
│ ├── create.go
│ └── list.go
├── ssl
│ ├── create.go
│ └── list.go
├── system
│ ├── dashboard.go
│ └── info.go
├── types
│ ├── app.go
│ ├── common.go
│ ├── database.go
│ ├── ssl.go
│ ├── system.go
│ └── website.go
└── website
│ ├── create.go
│ └── list.go
└── utils
├── common.go
├── constants.go
└── http_client.go
/.github/workflows/release-and-docker.yml:
--------------------------------------------------------------------------------
1 | name: Build and Release MCP-1Panel
2 |
3 | on:
4 | workflow_dispatch:
5 | inputs:
6 | version:
7 | description: 'Release version (e.g. v1.0.0)'
8 | required: true
9 | type: string
10 |
11 | env:
12 | IMAGE_NAME: 1panel/1panel-mcp-server
13 |
14 | jobs:
15 | build:
16 | runs-on: ubuntu-latest
17 | strategy:
18 | matrix:
19 | include:
20 | - goos: linux
21 | goarch: amd64
22 | - goos: linux
23 | goarch: arm64
24 | - goos: linux
25 | goarch: arm
26 | goarm: 7
27 | - goos: linux
28 | goarch: s390x
29 | - goos: linux
30 | goarch: ppc64le
31 |
32 | name: Build for ${{ matrix.goos }}-${{ matrix.goarch }}
33 | steps:
34 | - name: Checkout code
35 | uses: actions/checkout@v4
36 |
37 | - name: Set up Go
38 | uses: actions/setup-go@v5
39 | with:
40 | go-version: '1.23'
41 |
42 | - name: Build Binary
43 | run: |
44 | mkdir -p build
45 | FILE_NAME=mcp-1panel-${{ matrix.goos }}-${{ matrix.goarch }}
46 | if [ "${{ matrix.goarch }}" = "arm" ]; then
47 | FILE_NAME="${FILE_NAME}v${{ matrix.goarm }}"
48 | fi
49 | CGO_ENABLED=0 GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} GOARM=${{ matrix.goarm || '' }} \
50 | go build -trimpath -ldflags '-s -w' -o build/${FILE_NAME} ./main.go
51 | chmod +x build/${FILE_NAME}
52 |
53 | - name: Upload binary artifact
54 | uses: actions/upload-artifact@v4
55 | with:
56 | name: ${{ matrix.goos }}-${{ matrix.goarch }}-${{ matrix.goarm || 'default' }}
57 | path: build/*
58 |
59 | release:
60 | needs: build
61 | runs-on: ubuntu-latest
62 | name: Create GitHub Release
63 | steps:
64 | - name: Download all binary artifacts
65 | uses: actions/download-artifact@v4
66 | with:
67 | path: ./release-assets
68 |
69 | - name: Move all binaries to one folder
70 | run: |
71 | mkdir -p final-release
72 | find ./release-assets -type f -exec mv {} final-release/ \;
73 |
74 | - name: List final files
75 | run: ls -lh final-release
76 |
77 | - name: Create GitHub Release Draft
78 | uses: softprops/action-gh-release@v2
79 | with:
80 | tag_name: ${{ github.event.inputs.version }}
81 | name: ${{ github.event.inputs.version }}
82 | draft: true
83 | files: final-release/*
84 |
85 | docker:
86 | needs: build
87 | runs-on: ubuntu-latest
88 | name: Build and Push Docker Image
89 | steps:
90 | - name: Checkout Code
91 | uses: actions/checkout@v4
92 |
93 | - name: Set up QEMU
94 | uses: docker/setup-qemu-action@v3
95 | with:
96 | platforms: all
97 |
98 | - name: Set up Docker Buildx
99 | uses: docker/setup-buildx-action@v3
100 | id: buildx
101 |
102 | - name: Login to Docker Hub
103 | uses: docker/login-action@v3
104 | with:
105 | username: ${{ secrets.DOCKER_USERNAME }}
106 | password: ${{ secrets.DOCKER_PASSWORD }}
107 |
108 | - name: Build and Push Docker Image
109 | uses: docker/build-push-action@v5
110 | with:
111 | context: .
112 | platforms: linux/amd64,linux/arm64,linux/arm/v7,linux/s390x,linux/ppc64le
113 | push: true
114 | tags: |
115 | ${{ env.IMAGE_NAME }}:latest
116 | ${{ env.IMAGE_NAME }}:${{ github.event.inputs.version }}
117 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Mac
9 | .DS_Store
10 | */.DS_Store
11 |
12 | # VS Code
13 | .vscode
14 | *.project
15 | *.factorypath
16 | __debug*
17 |
18 | # IntelliJ IDEA
19 | .idea/*
20 | !.idea/icon.png
21 | *.iws
22 | *.iml
23 | *.ipr
24 |
25 | # Test binary, built with `go test -c`
26 | *.test
27 |
28 | # Output of the go coverage tool, specifically when used with LiteIDE
29 | *.out
30 |
31 | # Dependency directories
32 | build
33 | logs
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM golang:1.23.7 AS build
2 | # Set the working directory
3 | WORKDIR /build
4 |
5 | RUN go env -w GOMODCACHE=/root/.cache/go-build
6 |
7 | # Install dependencies
8 | COPY go.mod go.sum ./
9 | RUN --mount=type=cache,target=/root/.cache/go-build go mod download
10 |
11 | COPY . ./
12 | # Build the server
13 | RUN --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 go build -trimpath -ldflags '-s -w' \
14 | -o mcp-1panel main.go
15 |
16 | # Make a stage to run the app
17 | FROM alpine:3.21.3
18 | # Set the working directory
19 | WORKDIR /server
20 | # Copy the binary from the build stage
21 | COPY --from=build /build/mcp-1panel .
22 | # Command to run the server
23 | CMD ["./mcp-1panel", "stdio"]
24 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | GOCMD=go
2 | GOBUILD=$(GOCMD) build
3 | GOCLEAN=$(GOCMD) clean
4 | GOARCH=$(shell go env GOARCH)
5 | GOOS=$(shell go env GOOS )
6 |
7 | BASE_PATH := $(shell pwd)
8 | BUILD_PATH = $(BASE_PATH)/build
9 |
10 | MAIN_PATH=$(BASE_PATH)/main.go
11 | BIN_NAME=mcp-1panel
12 |
13 | .PHONY: build
14 |
15 | build:
16 | mkdir -p $(BUILD_PATH)
17 | cd $(BASE_PATH) \
18 | && CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) $(GOBUILD) -trimpath -ldflags '-s -w' -o $(BUILD_PATH)/$(BIN_NAME) $(MAIN_PATH)
19 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [English] | [中文(简体)]
2 |
3 | # 1Panel MCP Server
4 |
5 | **1Panel MCP Server** is an implementation of the Model Context Protocol (MCP) server for [1Panel](https://github.com/1Panel-dev/1Panel).
6 |
7 | ## Installation Methods
8 |
9 | ### Method 1: Download from Release Page (Recommended)
10 |
11 | 1. Visit the [Releases Page](https://github.com/1Panel-dev/mcp-1panel/releases) and download the executable file corresponding to your system.
12 |
13 | 2. Example installation (for amd64):
14 |
15 | ```bash
16 | chmod +x mcp-1panel-linux-amd64
17 | mv mcp-1panel-linux-amd64 /usr/local/bin/mcp-1panel
18 | ```
19 |
20 | ### Method 2: Build from Source
21 |
22 | Make sure Go 1.23 or later is installed locally. Then run:
23 |
24 | 1. Clone the repository:
25 |
26 | ```bash
27 | git clone https://github.com/1Panel-dev/mcp-1panel.git
28 | cd mcp-1panel
29 | ```
30 |
31 | 2. Build the executable:
32 |
33 | ```bash
34 | make build
35 | ```
36 |
37 | > Move ./build/mcp-1panel to a directory included in your system's PATH.
38 |
39 | ### Method 3: Install via go install
40 |
41 | Make sure Go 1.23 or later is installed locally. Then run:
42 |
43 | ```bash
44 | go install github.com/1Panel-dev/mcp-1panel@latest
45 | ```
46 |
47 | ### Method 4: Install via Docker
48 |
49 | Make sure Docker is correctly installed and configured on your machine.
50 |
51 | The official image supports the following architectures:
52 |
53 | - amd64
54 | - arm64
55 | - arm/v7
56 | - s390x
57 | - ppc64le
58 |
59 | ## Usage
60 |
61 | 1Panel MCP Server supports two running modes: `stdio` and `sse`.
62 |
63 | ### stdio Mode
64 |
65 | #### Using Local Binary
66 |
67 | In the configuration file of Cursor or Windsurf, add:
68 |
69 | ```json
70 | {
71 | "mcpServers": {
72 | "mcp-1panel": {
73 | "command": "mcp-1panel",
74 | "env": {
75 | "PANEL_ACCESS_TOKEN": "",
76 | "PANEL_HOST": "such as http://localhost:8080"
77 | }
78 | }
79 | }
80 | }
81 | ```
82 |
83 | #### Running in Docker
84 |
85 | ```json
86 | {
87 | "mcpServers": {
88 | "mcp-1panel": {
89 | "command": "docker",
90 | "args": [
91 | "run",
92 | "-i",
93 | "--rm",
94 | "-e",
95 | "PANEL_HOST",
96 | "-e",
97 | "PANEL_ACCESS_TOKEN",
98 | "1panel/1panel-mcp-server"
99 | ],
100 | "env": {
101 | "PANEL_HOST": "such as http://localhost:8080",
102 | "PANEL_ACCESS_TOKEN": ""
103 | }
104 | }
105 | }
106 | }
107 | ```
108 |
109 | ### sse Mode
110 |
111 | 1. Start the MCP Server:
112 |
113 | ```bash
114 | mcp-1panel -host http://localhost:8080 -token -transport sse -addr http://localhost:8000
115 | ```
116 |
117 | 2. Configure in Cursor or Windsurf:
118 |
119 | ```json
120 | {
121 | "mcpServers": {
122 | "mcp-1panel": {
123 | "url": "http://localhost:8000/sse"
124 | }
125 | }
126 | }
127 | ```
128 |
129 | #### Command Line Options
130 |
131 | - `-token`: 1Panel access token
132 | - `-host`: 1Panel access address
133 | - `-transport`: Transport type (stdio or sse, default: stdio)
134 | - `-addr`: Start SSE server address (default: http://localhost:8000)
135 |
136 | ## Available Tools
137 |
138 | The server provides various tools for interacting with 1Panel:
139 |
140 | | Tool | Category | Description |
141 | |-----------------------------|--------------|---------------------------|
142 | | **get_dashboard_info** | System | List dashboard status |
143 | | **get_system_info** | System | Get system information |
144 | | **list_websites** | Website | List all websites |
145 | | **create_website** | Website | Create a website |
146 | | **list_ssls** | Certificate | List all certificates |
147 | | **create_ssl** | Certificate | Create a certificate |
148 | | **list_installed_apps** | Application | List installed apps |
149 | | **install_openresty** | Application | Install OpenResty |
150 | | **install_mysql** | Application | Install MySQL |
151 | | **list_databases** | Database | List all databases |
152 | | **create_database** | Database | Create a database |
153 |
--------------------------------------------------------------------------------
/docs/README.zh-Hans.md:
--------------------------------------------------------------------------------
1 | # 1Panel MCP Server
2 |
3 | **1Panel MCP Server** 是 [1Panel](https://github.com/1Panel-dev/1Panel) 的 Model Context Protocol (MCP) 协议服务端实现。
4 |
5 | ---
6 |
7 | ## 安装方式
8 |
9 | ### ✅ 方式一:从 Release 页面下载安装包(推荐)
10 |
11 | 1. 访问 [Releases 页面](https://github.com/1Panel-dev/mcp-1panel/releases),下载对应系统的可执行文件。
12 |
13 | 2. 安装示例(以 `amd64` 为例):
14 |
15 | ```bash
16 | chmod +x mcp-1panel-linux-amd64
17 | mv mcp-1panel-linux-amd64 /usr/local/bin/mcp-1panel
18 | ```
19 |
20 | ---
21 |
22 | ### 🛠️ 方式二:通过源码构建
23 |
24 | 确保本地已安装 Go 1.23 或更高版本,执行以下命令:
25 |
26 | 1. 克隆代码仓库:
27 |
28 | ```bash
29 | git clone https://github.com/1Panel-dev/mcp-1panel.git
30 | cd mcp-1panel
31 | ```
32 |
33 | 2. 构建可执行文件:
34 |
35 | ```bash
36 | make build
37 | ```
38 |
39 | 3. 可执行文件生成路径为:`./build/mcp-1panel`,建议移动到系统 PATH 目录中。
40 |
41 | ---
42 |
43 | ### 🚀 方式三:通过 `go install` 安装
44 |
45 | 确保本地已安装 Go 1.23 或更高版本:
46 |
47 | ```bash
48 | go install github.com/1Panel-dev/mcp-1panel@latest
49 | ```
50 |
51 | ---
52 |
53 | ### 🐳 方式四:通过 Docker 安装
54 |
55 | 确保本地已正确安装并配置好 Docker。
56 |
57 | 我们官方提供的镜像支持以下五种架构:
58 |
59 | - `amd64`
60 | - `arm64`
61 | - `arm/v7`
62 | - `s390x`
63 | - `ppc64le`
64 |
65 | ---
66 |
67 | ## 使用方式
68 |
69 | 1Panel MCP Server 支持两种运行模式:**stdio** 和 **sse**
70 |
71 | ---
72 |
73 | ### 模式一:stdio(默认)
74 |
75 | #### 📦 使用本地二进制文件
76 |
77 | 在 Cursor 或 Windsurf 的配置文件中添加如下内容:
78 |
79 | ```json
80 | {
81 | "mcpServers": {
82 | "mcp-1panel": {
83 | "command": "mcp-1panel",
84 | "env": {
85 | "PANEL_ACCESS_TOKEN": "",
86 | "PANEL_HOST": "such as http://localhost:8080"
87 | }
88 | }
89 | }
90 | }
91 | ```
92 |
93 | #### 🐳 使用 Docker 方式运行
94 |
95 | ```json
96 | {
97 | "mcpServers": {
98 | "mcp-1panel": {
99 | "command": "docker",
100 | "args": [
101 | "run",
102 | "-i",
103 | "--rm",
104 | "-e",
105 | "PANEL_HOST",
106 | "-e",
107 | "PANEL_ACCESS_TOKEN",
108 | "1panel/1panel-mcp-server"
109 | ],
110 | "env": {
111 | "PANEL_HOST": "such as http://localhost:8080",
112 | "PANEL_ACCESS_TOKEN": ""
113 | }
114 | }
115 | }
116 | }
117 | ```
118 |
119 | ---
120 |
121 | ### 模式二:sse
122 |
123 | #### 🚀 启动 MCP Server:
124 |
125 | ```bash
126 | mcp-1panel -host http://localhost:8080 -token -transport sse -addr http://localhost:8000
127 | ```
128 |
129 | #### ⚙️ 配置 Cursor 或 Windsurf:
130 |
131 | ```json
132 | {
133 | "mcpServers": {
134 | "mcp-1panel": {
135 | "url": "http://localhost:8000/sse"
136 | }
137 | }
138 | }
139 | ```
140 |
141 | ---
142 |
143 | ### 🔧 命令行参数
144 |
145 | - `-token`: 1Panel 的访问令牌
146 | - `-host`: 1Panel 的地址,如:http://localhost:8080
147 | - `-transport`: 传输方式:`stdio` 或 `sse`,默认是 `stdio`
148 | - `-addr`: SSE 服务监听地址,默认是 `http://localhost:8000`
149 |
150 | ---
151 |
152 | ## 🧰 可用工具(Tools)
153 |
154 | 以下是 MCP Server 提供的工具列表,用于与 1Panel 交互:
155 |
156 | | 工具名称 | 分类 | 描述 |
157 | |-------------------------|-------------|----------------------------------|
158 | | `get_dashboard_info` | System | 获取仪表盘状态 |
159 | | `get_system_info` | System | 获取系统信息 |
160 | | `list_websites` | Website | 列出所有网站 |
161 | | `create_website` | Website | 创建新网站 |
162 | | `list_ssls` | Certificate | 列出所有证书 |
163 | | `create_ssl` | Certificate | 创建新证书 |
164 | | `list_installed_apps` | Application | 列出已安装应用 |
165 | | `install_openresty` | Application | 安装 OpenResty |
166 | | `install_mysql` | Application | 安装 MySQL |
167 | | `list_databases` | Database | 列出所有数据库 |
168 | | `create_database` | Database | 创建新数据库 |
169 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/1Panel-dev/mcp-1panel
2 |
3 | go 1.23
4 |
5 | toolchain go1.23.7
6 |
7 | require github.com/mark3labs/mcp-go v0.16.0
8 |
9 | require (
10 | github.com/google/uuid v1.6.0 // indirect
11 | github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
12 | )
13 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3 | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
4 | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
5 | github.com/mark3labs/mcp-go v0.16.0 h1:hNOr0EqhSUra5jm1Wv6+BOynzIa+bMtfP3zgde70MvY=
6 | github.com/mark3labs/mcp-go v0.16.0/go.mod h1:KmJndYv7GIgcPVwEKJjNcbhVQ+hJGJhrCCB/9xITzpE=
7 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
8 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
9 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
10 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
11 | github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
12 | github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
13 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
14 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
15 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "flag"
5 | "fmt"
6 | "github.com/1Panel-dev/mcp-1panel/operations/app"
7 | "github.com/1Panel-dev/mcp-1panel/operations/database"
8 | "github.com/1Panel-dev/mcp-1panel/operations/ssl"
9 | "github.com/1Panel-dev/mcp-1panel/operations/system"
10 | "github.com/1Panel-dev/mcp-1panel/operations/website"
11 | "github.com/1Panel-dev/mcp-1panel/utils"
12 | "log"
13 | "os"
14 | "path/filepath"
15 |
16 | "github.com/mark3labs/mcp-go/server"
17 | )
18 |
19 | var (
20 | Version = utils.Version
21 | )
22 |
23 | func setupLogger() (*os.File, error) {
24 | logDir := "logs"
25 | if err := os.MkdirAll(logDir, 0755); err != nil {
26 | fmt.Printf("create log dir error: %v\n", err)
27 | return nil, err
28 | }
29 |
30 | logFilePath := filepath.Join(logDir, "mcp-1panel.log")
31 | logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
32 | if err != nil {
33 | fmt.Printf("open log file error: %v\n", err)
34 | return nil, err
35 | }
36 |
37 | log.SetOutput(logFile)
38 | log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
39 | return logFile, nil
40 | }
41 |
42 | func newMCPServer() *server.MCPServer {
43 | return server.NewMCPServer(
44 | "github.com/1Panel-dev/mcp-1panel",
45 | Version,
46 | server.WithToolCapabilities(true),
47 | server.WithLogging(),
48 | )
49 | }
50 |
51 | func addTools(s *server.MCPServer) {
52 | s.AddTool(system.GetSystemInfoTool, system.GetSystemInfoHandle)
53 | s.AddTool(system.GetDashboardInfoTool, system.GetDashboardInfoHandle)
54 | s.AddTool(website.ListWebsitesTool, website.ListWebsiteHandle)
55 | s.AddTool(website.CreateWebsiteTool, website.CreateWebsiteHandle)
56 | s.AddTool(ssl.ListSSLsTool, ssl.ListSSLHandle)
57 | s.AddTool(app.InstallMySQLTool, app.InstallMySQLHandle)
58 | s.AddTool(app.InstallOpenRestyTool, app.InstallOpenRestyHandle)
59 | s.AddTool(app.ListInstalledAppsTool, app.ListInstalledAppsHandle)
60 | s.AddTool(ssl.CreateSSLTool, ssl.CreateSSLHandle)
61 | s.AddTool(database.ListDatabasesTool, database.ListDatabasesHandle)
62 | s.AddTool(database.CreateDatabaseTool, database.CreateDatabaseHandle)
63 | }
64 |
65 | func runServer(transport string, addr string) error {
66 | mcpServer := newMCPServer()
67 | addTools(mcpServer)
68 |
69 | if transport == "sse" {
70 | port, err := utils.GetPortFromAddr(addr)
71 | if err != nil {
72 | return err
73 | }
74 | log.Printf("SSE server listening on :%s", port)
75 | sseServer := server.NewSSEServer(mcpServer, server.WithBaseURL(addr))
76 | if err := sseServer.Start(fmt.Sprintf(":%s", port)); err != nil {
77 | log.Fatalf("Server error: %v", err)
78 | }
79 | } else {
80 | log.Printf("Run Stdio server")
81 | if err := server.ServeStdio(mcpServer); err != nil {
82 | log.Fatalf("Server error: %v", err)
83 | }
84 | }
85 | return nil
86 | }
87 |
88 | func main() {
89 | var (
90 | transport string
91 | accessToken string
92 | host string
93 | addr string
94 | )
95 | flag.StringVar(&transport, "transport", "stdio", "Transport type (stdio or sse)")
96 | flag.StringVar(&addr, "addr", "http://localhost:8000", "The base URL for mcp Server")
97 | flag.StringVar(&accessToken, "token", "", "1Panel api key")
98 | flag.StringVar(&host, "host", "", "1Panel host (example:http://127.0.0.1:9999)")
99 | flag.Parse()
100 |
101 | if accessToken != "" {
102 | utils.SetAccessToken(accessToken)
103 | }
104 | if host != "" {
105 | utils.SetHost(host)
106 | }
107 |
108 | if err := runServer(transport, addr); err != nil {
109 | fmt.Printf("server run error: %v\n", err)
110 | panic(err)
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/operations/app/install_mysql.go:
--------------------------------------------------------------------------------
1 | package app
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "fmt"
7 | "github.com/1Panel-dev/mcp-1panel/operations/types"
8 | "github.com/1Panel-dev/mcp-1panel/utils"
9 | "strings"
10 |
11 | "github.com/mark3labs/mcp-go/mcp"
12 | )
13 |
14 | const (
15 | InstallMySQL = "install_mysql"
16 | )
17 |
18 | var InstallMySQLTool = mcp.NewTool(
19 | InstallMySQL,
20 | mcp.WithDescription("install mysql, if not set name, default is mysql, if not set version, default is '', if not set root_password, default is '')"),
21 | mcp.WithString("name", mcp.Description("mysql name")),
22 | mcp.WithString("version", mcp.Description("mysql version, not support latest version"), mcp.DefaultString("")),
23 | mcp.WithString("root_password", mcp.Description("mysql root password"), mcp.DefaultString("")),
24 | mcp.WithNumber("port", mcp.Description("mysql port"), mcp.DefaultNumber(3306)),
25 | )
26 |
27 | func InstallMySQLHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
28 | var name string
29 | if request.Params.Arguments["name"] == nil {
30 | name = "mysql"
31 | } else {
32 | name = request.Params.Arguments["name"].(string)
33 | }
34 | var version string
35 | if request.Params.Arguments["version"] != nil {
36 | version = request.Params.Arguments["version"].(string)
37 | if version == "latest" {
38 | version = ""
39 | }
40 | }
41 | appRes := &types.AppRes{}
42 | _, err := utils.NewPanelClient("GET", "/apps/mysql").Request(appRes)
43 | if err != nil {
44 | return nil, err
45 | }
46 | exist := false
47 | for _, v := range appRes.Data.Versions {
48 | if v == version || strings.Contains(v, version) {
49 | version = v
50 | exist = true
51 | break
52 | }
53 | }
54 | if !exist {
55 | return nil, errors.New("version not found")
56 | }
57 | if version == "" {
58 | version = appRes.Data.Versions[0]
59 | }
60 | appID := appRes.Data.ID
61 | appDetailUrl := fmt.Sprintf("/apps/detail/%d/%s/app", appID, version)
62 | appDetailRes := &types.AppDetailRes{}
63 | _, err = utils.NewPanelClient("GET", appDetailUrl).Request(appDetailRes)
64 | if err != nil {
65 | return nil, err
66 | }
67 | appDetailID := appDetailRes.Data.ID
68 | var port float64
69 | if request.Params.Arguments["port"] != nil {
70 | port = request.Params.Arguments["port"].(float64)
71 | }
72 | if port == 0 {
73 | port = 3306
74 | }
75 | var rootPassword string
76 | if request.Params.Arguments["root_password"] != nil {
77 | rootPassword = request.Params.Arguments["root_password"].(string)
78 | }
79 | if rootPassword == "" {
80 | rootPassword = fmt.Sprintf("mysql_%s", utils.GetRandomStr(6))
81 | }
82 |
83 | req := &types.AppInstallCreate{
84 | AppDetailID: appDetailID,
85 | Name: name,
86 | Params: map[string]interface{}{
87 | "PANEL_APP_PORT_HTTP": port,
88 | "PANEL_DB_ROOT_PASSWORD": rootPassword,
89 | },
90 | }
91 | client := utils.NewPanelClient("POST", "/apps/install", utils.WithPayload(req))
92 | res := &types.Response{}
93 | return client.Request(res)
94 | }
95 |
--------------------------------------------------------------------------------
/operations/app/install_openresty.go:
--------------------------------------------------------------------------------
1 | package app
2 |
3 | import (
4 | "context"
5 | "fmt"
6 | "github.com/1Panel-dev/mcp-1panel/operations/types"
7 | "github.com/1Panel-dev/mcp-1panel/utils"
8 |
9 | "github.com/mark3labs/mcp-go/mcp"
10 | )
11 |
12 | const (
13 | InstallOpenResty = "install_openresty"
14 | )
15 |
16 | var InstallOpenRestyTool = mcp.NewTool(
17 | InstallOpenResty,
18 | mcp.WithDescription("install openresty, if not set name, default is openresty, if not set http_port, default is 80, if not set https_port, default is 443"),
19 | mcp.WithString("name", mcp.Description("openresty name"), mcp.DefaultString("openresty")),
20 | mcp.WithNumber("http_port", mcp.Description("openresty http port"), mcp.DefaultNumber(80)),
21 | mcp.WithNumber("https_port", mcp.Description("openresty https port"), mcp.DefaultNumber(443)),
22 | )
23 |
24 | func InstallOpenRestyHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
25 | var name string
26 | if request.Params.Arguments["name"] == nil {
27 | name = "openresty"
28 | } else {
29 | name = request.Params.Arguments["name"].(string)
30 | }
31 |
32 | var httpPort float64
33 | if request.Params.Arguments["http_port"] != nil {
34 | httpPort = request.Params.Arguments["http_port"].(float64)
35 | }
36 | if httpPort == 0 {
37 | httpPort = 80
38 | }
39 |
40 | var httpsPort float64
41 | if request.Params.Arguments["https_port"] != nil {
42 | httpsPort = request.Params.Arguments["https_port"].(float64)
43 | }
44 | if httpsPort == 0 {
45 | httpsPort = 443
46 | }
47 |
48 | appRes := &types.AppRes{}
49 | _, err := utils.NewPanelClient("GET", "/apps/openresty").Request(appRes)
50 | if err != nil {
51 | return nil, err
52 | }
53 | version := appRes.Data.Versions[0]
54 | appID := appRes.Data.ID
55 | appDetailUrl := fmt.Sprintf("/apps/detail/%d/%s/app", appID, version)
56 | appDetailRes := &types.AppDetailRes{}
57 | _, err = utils.NewPanelClient("GET", appDetailUrl).Request(appDetailRes)
58 | if err != nil {
59 | return nil, err
60 | }
61 |
62 | appDetailID := appDetailRes.Data.ID
63 |
64 | req := &types.AppInstallCreate{
65 | AppDetailID: appDetailID,
66 | Name: name,
67 | Params: map[string]interface{}{
68 | "PANEL_APP_PORT_HTTP": httpPort,
69 | "PANEL_APP_PORT_HTTPS": httpsPort,
70 | },
71 | }
72 | client := utils.NewPanelClient("POST", "/apps/install", utils.WithPayload(req))
73 | res := &types.Response{}
74 | return client.Request(res)
75 | }
76 |
--------------------------------------------------------------------------------
/operations/app/list_install.go:
--------------------------------------------------------------------------------
1 | package app
2 |
3 | import (
4 | "context"
5 | "github.com/1Panel-dev/mcp-1panel/operations/types"
6 | "github.com/1Panel-dev/mcp-1panel/utils"
7 |
8 | "github.com/mark3labs/mcp-go/mcp"
9 | )
10 |
11 | const (
12 | ListInstalledApps = "list_installed_apps"
13 | )
14 |
15 | var ListInstalledAppsTool = mcp.NewTool(
16 | ListInstalledApps,
17 | mcp.WithDescription("list installed apps"),
18 | )
19 |
20 | func ListInstalledAppsHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
21 | req := &types.PageRequest{
22 | Page: 1,
23 | PageSize: 500,
24 | }
25 | appListRes := &types.AppInstalledListResponse{}
26 | return utils.NewPanelClient("POST", "/apps/installed/search", utils.WithPayload(req)).Request(appListRes)
27 | }
28 |
--------------------------------------------------------------------------------
/operations/database/create.go:
--------------------------------------------------------------------------------
1 | package database
2 |
3 | import (
4 | "context"
5 | "encoding/base64"
6 | "errors"
7 | "github.com/1Panel-dev/mcp-1panel/operations/types"
8 | "github.com/1Panel-dev/mcp-1panel/utils"
9 |
10 | "github.com/mark3labs/mcp-go/mcp"
11 | )
12 |
13 | const (
14 | CreateDatabase = "create_database"
15 | )
16 |
17 | var CreateDatabaseTool = mcp.NewTool(
18 | CreateDatabase,
19 | mcp.WithDescription("create a database by type name and password"),
20 | mcp.WithString("database_type", mcp.Description("installed database app type, support mysql and postgresql"), mcp.DefaultString("mysql"), mcp.Required()),
21 | mcp.WithString("database", mcp.Description("installed database app name"), mcp.DefaultString(""), mcp.Required()),
22 | mcp.WithString("name", mcp.Description("database name"), mcp.DefaultString(""), mcp.Required()),
23 | mcp.WithString("username", mcp.Description("database username"), mcp.DefaultString("")),
24 | mcp.WithString("password", mcp.Description("database password"), mcp.DefaultString("")),
25 | )
26 |
27 | func CreateDatabaseHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
28 | var (
29 | database string
30 | password string
31 | name string
32 | databaseType string
33 | username string
34 | )
35 | if request.Params.Arguments["database"] == nil {
36 | return nil, errors.New("database name is required")
37 | }
38 | database = request.Params.Arguments["database"].(string)
39 | if request.Params.Arguments["database_type"] == nil {
40 | return nil, errors.New("database type is required")
41 | }
42 | databaseType = request.Params.Arguments["database_type"].(string)
43 | if databaseType != "mysql" && databaseType != "postgresql" {
44 | return nil, errors.New("database type is invalid, support mysql and postgresql")
45 | }
46 | if request.Params.Arguments["name"] == nil {
47 | return nil, errors.New("name is required")
48 | }
49 | name = request.Params.Arguments["name"].(string)
50 | if request.Params.Arguments["password"] == nil {
51 | password = utils.GetRandomStr(12)
52 | } else {
53 | password = request.Params.Arguments["password"].(string)
54 | }
55 | encodedPassword := base64.StdEncoding.EncodeToString([]byte(password))
56 |
57 | if request.Params.Arguments["username"] == nil {
58 | username = name
59 | } else {
60 | username = request.Params.Arguments["username"].(string)
61 | }
62 |
63 | createReq := &types.CreateDatabaseRequest{
64 | Database: database,
65 | Password: encodedPassword,
66 | Type: databaseType,
67 | Name: name,
68 | From: "local",
69 | Username: username,
70 | }
71 | var createUrl string
72 | if databaseType == "mysql" {
73 | createUrl = "/databases"
74 | createReq.Format = "utf8mb4"
75 | createReq.Permission = "%"
76 | } else {
77 | createUrl = "/databases/pg"
78 | createReq.Format = "UTF8"
79 | }
80 | client := utils.NewPanelClient("POST", createUrl, utils.WithPayload(createReq))
81 | res := &types.Response{}
82 | return client.Request(res)
83 | }
84 |
--------------------------------------------------------------------------------
/operations/database/list.go:
--------------------------------------------------------------------------------
1 | package database
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "github.com/1Panel-dev/mcp-1panel/operations/types"
7 | "github.com/1Panel-dev/mcp-1panel/utils"
8 |
9 | "github.com/mark3labs/mcp-go/mcp"
10 | )
11 |
12 | const (
13 | ListDatabases = "list_databases"
14 | )
15 |
16 | var ListDatabasesTool = mcp.NewTool(
17 | ListDatabases,
18 | mcp.WithDescription("list databases by name"),
19 | mcp.WithString("name", mcp.Description("database name"), mcp.DefaultString(""), mcp.Required()),
20 | )
21 |
22 | func ListDatabasesHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
23 | var database string
24 | if request.Params.Arguments["name"] != nil {
25 | database = request.Params.Arguments["name"].(string)
26 | }
27 | if database == "" {
28 | return nil, errors.New("database name is required")
29 | }
30 | pageReq := &types.ListDatabaseRequest{
31 | PageRequest: types.PageRequest{
32 | Page: 1,
33 | PageSize: 500,
34 | },
35 | Order: "null",
36 | OrderBy: "created_at",
37 | Database: database,
38 | }
39 | databaseListRes := &types.DatabaseListResponse{}
40 | client := utils.NewPanelClient("POST", "/databases/search", utils.WithPayload(pageReq))
41 | return client.Request(databaseListRes)
42 | }
43 |
--------------------------------------------------------------------------------
/operations/ssl/create.go:
--------------------------------------------------------------------------------
1 | package ssl
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "github.com/1Panel-dev/mcp-1panel/operations/types"
7 | "github.com/1Panel-dev/mcp-1panel/utils"
8 | "strings"
9 |
10 | "github.com/mark3labs/mcp-go/mcp"
11 | )
12 |
13 | const (
14 | CreateSSL = "create_ssl"
15 | )
16 |
17 | var CreateSSLTool = mcp.NewTool(
18 | CreateSSL,
19 | mcp.WithDescription("create ssl"),
20 | mcp.WithString("domain", mcp.Description("domain"), mcp.Required()),
21 | mcp.WithString("provider", mcp.Description("provider support dnsAccount,http"), mcp.Required(), mcp.DefaultString("dnsAccount")),
22 | mcp.WithString("dnsAccount", mcp.Description("dnsAccount"), mcp.DefaultString("")),
23 | )
24 |
25 | func CreateSSLHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
26 | if request.Params.Arguments["domain"] == nil {
27 | return nil, errors.New("domain is required")
28 | }
29 | domain := request.Params.Arguments["domain"].(string)
30 | if request.Params.Arguments["provider"] == nil {
31 | return nil, errors.New("provider is required")
32 | }
33 | provider := request.Params.Arguments["provider"].(string)
34 | if provider != "dnsAccount" && provider != "http" {
35 | return nil, errors.New("provider must be dnsAccount or http")
36 | }
37 |
38 | acmeRes := &types.ListAcmeRes{}
39 | pageReq := &types.PageRequest{
40 | Page: 1,
41 | PageSize: 500,
42 | }
43 | client := utils.NewPanelClient("POST", "/websites/acme/search", utils.WithPayload(pageReq))
44 | _, err := client.Request(acmeRes)
45 | if err != nil {
46 | return nil, err
47 | }
48 | if len(acmeRes.Data.Items) == 0 {
49 | return nil, errors.New("no acme account found")
50 | }
51 | acme := acmeRes.Data.Items[0]
52 |
53 | var dnsAccountID uint
54 | if provider == "dnsAccount" {
55 | dnsAccountRes := &types.ListDNSAccountRes{}
56 | client = utils.NewPanelClient("POST", "/websites/dns/search", utils.WithPayload(pageReq))
57 | _, err = client.Request(dnsAccountRes)
58 | if err != nil {
59 | return nil, err
60 | }
61 | if len(dnsAccountRes.Data.Items) == 0 {
62 | return nil, errors.New("no dns account found")
63 | }
64 | var dnsName string
65 | if request.Params.Arguments["dnsAccount"] != nil {
66 | dnsName = request.Params.Arguments["dnsAccount"].(string)
67 | }
68 | if dnsName != "" {
69 | checkName := strings.ToLower(dnsName)
70 | for _, dnsAccount := range dnsAccountRes.Data.Items {
71 | if strings.Contains(strings.ToLower(dnsAccount.Name), checkName) || strings.Contains(strings.ToLower(dnsAccount.Type), checkName) {
72 | dnsAccountID = dnsAccount.ID
73 | break
74 | }
75 | }
76 | }
77 | if dnsAccountID == 0 {
78 | dnsAccountID = dnsAccountRes.Data.Items[0].ID
79 | }
80 | }
81 |
82 | req := &types.CreateSSLRequest{
83 | PrimaryDomain: domain,
84 | Provider: provider,
85 | AcmeAccountID: acme.ID,
86 | DnsAccountID: dnsAccountID,
87 | KeyType: "P256",
88 | }
89 | client = utils.NewPanelClient("POST", "/websites/ssl", utils.WithPayload(req))
90 | res := &types.Response{}
91 | return client.Request(res)
92 | }
93 |
--------------------------------------------------------------------------------
/operations/ssl/list.go:
--------------------------------------------------------------------------------
1 | package ssl
2 |
3 | import (
4 | "context"
5 | "github.com/1Panel-dev/mcp-1panel/operations/types"
6 | "github.com/1Panel-dev/mcp-1panel/utils"
7 |
8 | "github.com/mark3labs/mcp-go/mcp"
9 | )
10 |
11 | const (
12 | ListSSLs = "list_ssls"
13 | )
14 |
15 | var ListSSLsTool = mcp.NewTool(
16 | ListSSLs,
17 | mcp.WithDescription("list ssls"),
18 | )
19 |
20 | func ListSSLHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
21 | req := &types.PageRequest{
22 | Page: 1,
23 | PageSize: 500,
24 | }
25 | client := utils.NewPanelClient("POST", "/websites/ssl/search", utils.WithPayload(req))
26 | listWebsiteSSLRes := &types.ListWebsiteSSLRes{}
27 | return client.Request(listWebsiteSSLRes)
28 | }
29 |
--------------------------------------------------------------------------------
/operations/system/dashboard.go:
--------------------------------------------------------------------------------
1 | package system
2 |
3 | import (
4 | "context"
5 | "github.com/1Panel-dev/mcp-1panel/operations/types"
6 | "github.com/1Panel-dev/mcp-1panel/utils"
7 |
8 | "github.com/mark3labs/mcp-go/mcp"
9 | )
10 |
11 | const (
12 | GetDashboardInfo = "get_dashboard_info"
13 | )
14 |
15 | var GetDashboardInfoTool = mcp.NewTool(GetDashboardInfo, mcp.WithDescription(
16 | "show dashboard info"))
17 |
18 | func GetDashboardInfoHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
19 | client := utils.NewPanelClient("GET", "/dashboard/base/all/all")
20 | osInfo := &types.DashboardRes{}
21 | return client.Request(osInfo)
22 | }
23 |
--------------------------------------------------------------------------------
/operations/system/info.go:
--------------------------------------------------------------------------------
1 | package system
2 |
3 | import (
4 | "context"
5 | "github.com/1Panel-dev/mcp-1panel/operations/types"
6 | "github.com/1Panel-dev/mcp-1panel/utils"
7 |
8 | "github.com/mark3labs/mcp-go/mcp"
9 | )
10 |
11 | const (
12 | GetSystemInfo = "get_system_info"
13 | )
14 |
15 | var GetSystemInfoTool = mcp.NewTool(GetSystemInfo, mcp.WithDescription(
16 | "show host system information, The unit of diskSize is bytes"))
17 |
18 | func GetSystemInfoHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
19 | client := utils.NewPanelClient("GET", "/dashboard/base/os")
20 | osInfo := &types.OsInfoRes{}
21 | return client.Request(osInfo)
22 | }
23 |
--------------------------------------------------------------------------------
/operations/types/app.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 |
4 | type AppInstallCreate struct {
5 | AppDetailID uint `json:"appDetailId"`
6 | Params map[string]interface{} `json:"params"`
7 | Name string `json:"name"`
8 | }
9 |
10 | type AppRes struct {
11 | Response
12 | Data App `json:"data"`
13 | }
14 |
15 | type App struct {
16 | ID uint `json:"id"`
17 | Versions []string `json:"versions"`
18 | }
19 |
20 | type AppDetailRes struct {
21 | Response
22 | Data AppDetail `json:"data"`
23 | }
24 |
25 | type AppDetail struct {
26 | ID uint `json:"id"`
27 | }
28 | type AppInstall struct {
29 | ID uint `json:"id"`
30 | Name string `json:"name"`
31 | Version string `json:"version"`
32 | Status string `json:"status"`
33 | AppName string `json:"appName"`
34 | }
35 |
36 | type AppInstalledListResponse struct {
37 | Response
38 | Data struct {
39 | PageResult
40 | Items []AppInstall `json:"items"`
41 | } `json:"data"`
42 | }
--------------------------------------------------------------------------------
/operations/types/common.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | type Response struct {
4 | Code int `json:"code"`
5 | Message string `json:"message"`
6 | }
7 |
8 | type PageResult struct {
9 | Total int64 `json:"total"`
10 | }
11 |
12 | type PageRequest struct {
13 | Page int `json:"page"`
14 | PageSize int `json:"pageSize"`
15 | Name string `json:"name"`
16 | }
17 |
--------------------------------------------------------------------------------
/operations/types/database.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | type Database struct {
4 | ID uint `json:"id"`
5 | Name string `json:"name"`
6 | Username string `json:"username"`
7 | }
8 |
9 | type DatabaseListResponse struct {
10 | Response
11 | Data struct {
12 | PageResult
13 | Items []Database `json:"items"`
14 | } `json:"data"`
15 | }
16 |
17 | type ListDatabaseRequest struct {
18 | PageRequest
19 | Order string `json:"order"`
20 | OrderBy string `json:"orderBy"`
21 | Database string `json:"database"`
22 | }
23 |
24 |
25 | type CreateDatabaseRequest struct {
26 | Database string `json:"database"`
27 | Password string `json:"password"`
28 | Type string `json:"type"`
29 | Format string `json:"format"`
30 | From string `json:"from"`
31 | Permission string `json:"permission"`
32 | Name string `json:"name"`
33 | Username string `json:"username"`
34 | Superuser bool `json:"superuser"`
35 | }
36 |
37 |
--------------------------------------------------------------------------------
/operations/types/ssl.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import "time"
4 |
5 | type ListWebsiteSSLRes struct {
6 | Response
7 | Data struct {
8 | PageResult
9 | Items []WebsiteSSL `json:"items"`
10 | } `json:"data"`
11 | }
12 |
13 | type WebsiteSSL struct {
14 | ID uint `json:"id"`
15 | PrimaryDomain string `json:"primaryDomain"`
16 | Domains string `json:"domains"`
17 | Provider string `json:"provider"`
18 | Organization string `json:"organization"`
19 | AutoRenew bool `json:"autoRenew"`
20 | ExpireDate time.Time `json:"expireDate"`
21 | StartDate time.Time `json:"startDate"`
22 | Status string `json:"status"`
23 | }
24 |
25 | type CreateSSLRequest struct {
26 | PrimaryDomain string `json:"primaryDomain"`
27 | Domains string `json:"domains"`
28 | Provider string `json:"provider"`
29 | AcmeAccountID uint `json:"acmeAccountId"`
30 | DnsAccountID uint `json:"dnsAccountId"`
31 | KeyType string `json:"keyType"`
32 | }
33 |
34 | type ListAcmeRes struct {
35 | Response
36 | Data AcmeDTO `json:"data"`
37 | }
38 |
39 | type AcmeDTO struct {
40 | PageResult
41 | Items []Acme `json:"items"`
42 | }
43 |
44 | type Acme struct {
45 | ID uint `json:"id"`
46 | Email string `json:"email"`
47 | Provider string `json:"provider"`
48 | }
49 |
50 | type ListDNSAccountRes struct {
51 | Response
52 | Data struct {
53 | PageResult
54 | Items []DNSAccount `json:"items"`
55 | } `json:"data"`
56 | }
57 |
58 | type DNSAccount struct {
59 | ID uint `json:"id"`
60 | Name string `json:"name"`
61 | Type string `json:"type"`
62 | }
--------------------------------------------------------------------------------
/operations/types/system.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import "time"
4 |
5 | type OsInfo struct {
6 | OS string `json:"os"`
7 | Platform string `json:"platform"`
8 | PlatformFamily string `json:"platformFamily"`
9 | KernelArch string `json:"kernelArch"`
10 | KernelVersion string `json:"kernelVersion"`
11 |
12 | DiskSize int64 `json:"diskSize"`
13 | }
14 |
15 | type OsInfoRes struct {
16 | Response
17 | Data OsInfo `json:"data"`
18 | }
19 |
20 | type DashboardRes struct {
21 | Response
22 | Data DashboardBase `json:"data"`
23 | }
24 |
25 | type DashboardBase struct {
26 | WebsiteNumber int `json:"websiteNumber"`
27 | DatabaseNumber int `json:"databaseNumber"`
28 | CronjobNumber int `json:"cronjobNumber"`
29 | AppInstalledNumber int `json:"appInstalledNumber"`
30 |
31 | Hostname string `json:"hostname"`
32 | OS string `json:"os"`
33 | Platform string `json:"platform"`
34 | PlatformFamily string `json:"platformFamily"`
35 | PlatformVersion string `json:"platformVersion"`
36 | KernelArch string `json:"kernelArch"`
37 | KernelVersion string `json:"kernelVersion"`
38 | VirtualizationSystem string `json:"virtualizationSystem"`
39 | IpV4Addr string `json:"ipV4Addr"`
40 | SystemProxy string `json:"systemProxy"`
41 |
42 | CPUCores int `json:"cpuCores"`
43 | CPULogicalCores int `json:"cpuLogicalCores"`
44 | CPUModelName string `json:"cpuModelName"`
45 |
46 | CurrentInfo DashboardCurrent `json:"currentInfo"`
47 | }
48 |
49 | type DashboardCurrent struct {
50 | Uptime uint64 `json:"uptime"`
51 | TimeSinceUptime string `json:"timeSinceUptime"`
52 |
53 | Procs uint64 `json:"procs"`
54 |
55 | Load1 float64 `json:"load1"`
56 | Load5 float64 `json:"load5"`
57 | Load15 float64 `json:"load15"`
58 | LoadUsagePercent float64 `json:"loadUsagePercent"`
59 |
60 | CPUPercent []float64 `json:"cpuPercent"`
61 | CPUUsedPercent float64 `json:"cpuUsedPercent"`
62 | CPUUsed float64 `json:"cpuUsed"`
63 | CPUTotal int `json:"cpuTotal"`
64 |
65 | MemoryTotal uint64 `json:"memoryTotal"`
66 | MemoryAvailable uint64 `json:"memoryAvailable"`
67 | MemoryUsed uint64 `json:"memoryUsed"`
68 | MemoryUsedPercent float64 `json:"memoryUsedPercent"`
69 |
70 | SwapMemoryTotal uint64 `json:"swapMemoryTotal"`
71 | SwapMemoryAvailable uint64 `json:"swapMemoryAvailable"`
72 | SwapMemoryUsed uint64 `json:"swapMemoryUsed"`
73 | SwapMemoryUsedPercent float64 `json:"swapMemoryUsedPercent"`
74 |
75 | IOReadBytes uint64 `json:"ioReadBytes"`
76 | IOWriteBytes uint64 `json:"ioWriteBytes"`
77 | IOCount uint64 `json:"ioCount"`
78 | IOReadTime uint64 `json:"ioReadTime"`
79 | IOWriteTime uint64 `json:"ioWriteTime"`
80 |
81 | DiskData []DiskInfo `json:"diskData"`
82 |
83 | NetBytesSent uint64 `json:"netBytesSent"`
84 | NetBytesRecv uint64 `json:"netBytesRecv"`
85 |
86 | GPUData []GPUInfo `json:"gpuData"`
87 | XPUData []XPUInfo `json:"xpuData"`
88 |
89 | ShotTime time.Time `json:"shotTime"`
90 | }
91 |
92 | type DiskInfo struct {
93 | Path string `json:"path"`
94 | Type string `json:"type"`
95 | Device string `json:"device"`
96 | Total uint64 `json:"total"`
97 | Free uint64 `json:"free"`
98 | Used uint64 `json:"used"`
99 | UsedPercent float64 `json:"usedPercent"`
100 |
101 | InodesTotal uint64 `json:"inodesTotal"`
102 | InodesUsed uint64 `json:"inodesUsed"`
103 | InodesFree uint64 `json:"inodesFree"`
104 | InodesUsedPercent float64 `json:"inodesUsedPercent"`
105 | }
106 |
107 | type GPUInfo struct {
108 | Index uint `json:"index"`
109 | ProductName string `json:"productName"`
110 | GPUUtil string `json:"gpuUtil"`
111 | Temperature string `json:"temperature"`
112 | PerformanceState string `json:"performanceState"`
113 | PowerUsage string `json:"powerUsage"`
114 | PowerDraw string `json:"powerDraw"`
115 | MaxPowerLimit string `json:"maxPowerLimit"`
116 | MemoryUsage string `json:"memoryUsage"`
117 | MemUsed string `json:"memUsed"`
118 | MemTotal string `json:"memTotal"`
119 | FanSpeed string `json:"fanSpeed"`
120 | }
121 |
122 | type XPUInfo struct {
123 | DeviceID int `json:"deviceID"`
124 | DeviceName string `json:"deviceName"`
125 | Memory string `json:"memory"`
126 | Temperature string `json:"temperature"`
127 | MemoryUsed string `json:"memoryUsed"`
128 | Power string `json:"power"`
129 | MemoryUtil string `json:"memoryUtil"`
130 | }
131 |
--------------------------------------------------------------------------------
/operations/types/website.go:
--------------------------------------------------------------------------------
1 | package types
2 |
3 | import "time"
4 |
5 | type ListWebsiteRes struct {
6 | Response
7 | Data struct {
8 | PageResult
9 | Items []WebsiteRes `json:"items"`
10 | } `json:"data"`
11 | }
12 |
13 | type ListWebsiteRequest struct {
14 | PageRequest
15 | Order string `json:"order"`
16 | OrderBy string `json:"orderBy"`
17 | }
18 |
19 | type CreateWebsiteRequest struct {
20 | PrimaryDomain string `json:"primaryDomain"`
21 | Alias string `json:"alias"`
22 | Type string `json:"type"`
23 | WebsiteGroupID uint `json:"websiteGroupId"`
24 | Proxy string `json:"proxy"`
25 | AppType string `json:"appType"`
26 | }
27 |
28 | type GroupRequest struct {
29 | Type string `json:"type"`
30 | }
31 |
32 | type GroupRes struct {
33 | Response
34 | Data []Group `json:"data"`
35 | }
36 |
37 | type Group struct {
38 | ID uint `json:"id"`
39 | IsDefault bool `json:"isDefault"`
40 | }
41 |
42 | type WebsiteRes struct {
43 | ID uint `json:"id"`
44 | CreatedAt time.Time `json:"createdAt"`
45 | Protocol string `json:"protocol"`
46 | PrimaryDomain string `json:"primaryDomain"`
47 | Type string `json:"type"`
48 | Alias string `json:"alias"`
49 | Remark string `json:"remark"`
50 | Status string `json:"status"`
51 | ExpireDate time.Time `json:"expireDate"`
52 | AppName string `json:"appName"`
53 | RuntimeName string `json:"runtimeName"`
54 | SSLExpireDate time.Time `json:"sslExpireDate"`
55 | }
56 |
--------------------------------------------------------------------------------
/operations/website/create.go:
--------------------------------------------------------------------------------
1 | package website
2 |
3 | import (
4 | "context"
5 | "errors"
6 | "github.com/1Panel-dev/mcp-1panel/operations/types"
7 | "github.com/1Panel-dev/mcp-1panel/utils"
8 |
9 | "github.com/mark3labs/mcp-go/mcp"
10 | )
11 |
12 | const (
13 | CreateWebsite = "create_website"
14 | )
15 |
16 | var CreateWebsiteTool = mcp.NewTool(CreateWebsite,
17 | mcp.WithDescription("create website"),
18 | mcp.WithString("domain", mcp.Description("domain"), mcp.Required()),
19 | mcp.WithString("website_type", mcp.Description("website type,only support static and proxy"), mcp.Required()),
20 | mcp.WithString("proxy_address", mcp.Description("proxy address,only support for proxy website"), mcp.Required()),
21 | )
22 |
23 | func CreateWebsiteHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
24 | if request.Params.Arguments["domain"] == nil {
25 | return nil, errors.New("domain is required")
26 | }
27 | domain := request.Params.Arguments["domain"].(string)
28 | alias := domain
29 | var proxyAddress string
30 | if request.Params.Arguments["website_type"] == "proxy" {
31 | if request.Params.Arguments["proxy_address"] == nil {
32 | return nil, errors.New("proxy_address is required")
33 | }
34 | proxyAddress = request.Params.Arguments["proxy_address"].(string)
35 | }
36 |
37 | groupReq := &types.GroupRequest{
38 | Type: "website",
39 | }
40 | groupRes := &types.GroupRes{}
41 | _, err := utils.NewPanelClient("POST", "/groups/search", utils.WithPayload(groupReq)).Request(groupRes)
42 | if err != nil {
43 | return nil, err
44 | }
45 | var groupID uint
46 | for _, group := range groupRes.Data {
47 | if group.IsDefault {
48 | groupID = group.ID
49 | break
50 | }
51 | }
52 |
53 | req := &types.CreateWebsiteRequest{
54 | PrimaryDomain: domain,
55 | Alias: alias,
56 | Type: request.Params.Arguments["website_type"].(string),
57 | WebsiteGroupID: groupID,
58 | Proxy: proxyAddress,
59 | AppType: "new",
60 | }
61 | res := &types.Response{}
62 | return utils.NewPanelClient("POST", "/websites", utils.WithPayload(req)).Request(res)
63 | }
64 |
--------------------------------------------------------------------------------
/operations/website/list.go:
--------------------------------------------------------------------------------
1 | package website
2 |
3 | import (
4 | "context"
5 | "github.com/1Panel-dev/mcp-1panel/operations/types"
6 | "github.com/1Panel-dev/mcp-1panel/utils"
7 |
8 | "github.com/mark3labs/mcp-go/mcp"
9 | )
10 |
11 | const (
12 | ListWebsites = "list_websites"
13 | )
14 |
15 | var ListWebsitesTool = mcp.NewTool(
16 | ListWebsites,
17 | mcp.WithDescription("list websites"),
18 | mcp.WithString("name", mcp.Description("search by website name")),
19 | )
20 |
21 | func ListWebsiteHandle(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
22 | req := &types.ListWebsiteRequest{
23 | Order: "null",
24 | OrderBy: "created_at",
25 | PageRequest: types.PageRequest{
26 | Page: 1,
27 | PageSize: 500,
28 | Name: "",
29 | },
30 | }
31 | client := utils.NewPanelClient("POST", "/websites/search", utils.WithPayload(req))
32 | listWebsiteRes := &types.ListWebsiteRes{}
33 | return client.Request(listWebsiteRes)
34 | }
35 |
--------------------------------------------------------------------------------
/utils/common.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 | "net/url"
7 | "strings"
8 | )
9 |
10 |
11 | func GetRandomStr(e int) string {
12 | const charset = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"
13 | var result strings.Builder
14 | for i := 0; i < e; i++ {
15 | index := rand.Intn(len(charset))
16 | result.WriteByte(charset[index])
17 | }
18 | return result.String()
19 | }
20 |
21 | func GetPortFromAddr(addr string) (string, error) {
22 | parsedURL, err := url.Parse(addr)
23 | if err != nil {
24 | return "", err
25 | }
26 |
27 | hostPort := parsedURL.Host
28 | if strings.Contains(hostPort, ":") {
29 | parts := strings.Split(hostPort, ":")
30 | return parts[len(parts)-1], nil
31 | }
32 |
33 | return "", fmt.Errorf("port not found")
34 | }
35 |
--------------------------------------------------------------------------------
/utils/constants.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | var (
4 | Version = "0.0.1"
5 |
6 | ApiBase = "/api/v1"
7 | )
8 |
--------------------------------------------------------------------------------
/utils/http_client.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "bytes"
5 | "crypto/md5"
6 | "encoding/hex"
7 | "encoding/json"
8 | "errors"
9 | "fmt"
10 | "io"
11 | "net/http"
12 | "net/url"
13 | "os"
14 | "runtime"
15 | "strconv"
16 | "time"
17 |
18 | "github.com/mark3labs/mcp-go/mcp"
19 | )
20 |
21 | var (
22 | accessToken string
23 | apiBase string
24 | timestamp string
25 | )
26 |
27 | func md5Sum(data string) string {
28 | h := md5.New()
29 | h.Write([]byte(data))
30 | return hex.EncodeToString(h.Sum(nil))
31 | }
32 |
33 | func SetAccessToken(token string) {
34 | timestamp = strconv.FormatInt(time.Now().Unix(), 10)
35 | accessToken = md5Sum("1panel" + token + timestamp)
36 | }
37 |
38 | func SetHost(host string) {
39 | apiBase = fmt.Sprintf("%s%s", host, ApiBase)
40 | }
41 |
42 | func GetAccessToken() string {
43 | if accessToken != "" {
44 | return accessToken
45 | }
46 | if token := os.Getenv("PANEL_ACCESS_TOKEN"); token != "" {
47 | SetAccessToken(token)
48 | return accessToken
49 | }
50 | return accessToken
51 | }
52 |
53 | func GetApiBase() string {
54 | if apiBase != "" {
55 | return apiBase
56 | }
57 | if host := os.Getenv("PANEL_HOST"); host != "" {
58 | SetHost(host)
59 | return apiBase
60 | }
61 | return apiBase
62 | }
63 |
64 | type PanelClient struct {
65 | Url string
66 | Method string
67 | Payload interface{}
68 | Headers map[string]string
69 | Response *http.Response
70 | parsedUrl *url.URL
71 | Query map[string]string
72 | }
73 |
74 | type Option func(client *PanelClient)
75 |
76 | type ErrMsg struct {
77 | Message string `json:"message"`
78 | }
79 |
80 | type PanelError struct {
81 | Code int
82 | Message string
83 | Details string
84 | }
85 |
86 | func (e *PanelError) Error() string {
87 | return fmt.Sprintf("Panel API error: %s (code: %d)", e.Message, e.Code)
88 | }
89 |
90 | func NewPanelError(code int, message, details string) *PanelError {
91 | return &PanelError{
92 | Code: code,
93 | Message: message,
94 | Details: details,
95 | }
96 | }
97 |
98 | func NewAPIError(statusCode int, body []byte) error {
99 | var errMsg ErrMsg
100 | if err := json.Unmarshal(body, &errMsg); err != nil {
101 | details := string(body)
102 | if details == "" {
103 | details = "No error details available"
104 | }
105 | return NewPanelError(statusCode, http.StatusText(statusCode), details)
106 | }
107 |
108 | return NewPanelError(statusCode, http.StatusText(statusCode), errMsg.Message)
109 | }
110 |
111 | func NewAuthError() error {
112 | return NewPanelError(401, "Unauthorized", "Panel access token is missing or invalid")
113 | }
114 |
115 | func IsAuthError(err error) bool {
116 | var panelErr *PanelError
117 | if errors.As(err, &panelErr) {
118 | return panelErr.Code == 401
119 | }
120 | return false
121 | }
122 |
123 | func NewNetworkError(err error) error {
124 | return NewPanelError(0, "Network Error", err.Error())
125 | }
126 |
127 | func IsNetworkError(err error) bool {
128 | var panelErr *PanelError
129 | if errors.As(err, &panelErr) {
130 | return panelErr.Code == 0
131 | }
132 | return false
133 | }
134 |
135 | func NewInternalError(err error) error {
136 | return NewPanelError(500, "Internal Error", err.Error())
137 | }
138 |
139 | func IsAPIError(err error) bool {
140 | var panelError *PanelError
141 | ok := errors.As(err, &panelError)
142 | return ok
143 | }
144 |
145 | func NewPanelClient(method, urlPath string, opts ...Option) *PanelClient {
146 | urlString := GetApiBase() + urlPath
147 | parsedUrl, err := url.Parse(urlString)
148 | if err != nil {
149 | panic(err)
150 | }
151 |
152 | client := &PanelClient{
153 | Method: method,
154 | Url: parsedUrl.String(),
155 | parsedUrl: parsedUrl,
156 | Headers: make(map[string]string),
157 | }
158 |
159 | for _, opt := range opts {
160 | opt(client)
161 | }
162 | return client
163 | }
164 |
165 | func WithQuery(query map[string]interface{}) Option {
166 | return func(client *PanelClient) {
167 | parsedQuery := make(map[string]string)
168 | if query != nil {
169 | queryParams := client.parsedUrl.Query()
170 | for k, v := range query {
171 | parsedValue := ""
172 | switch v := v.(type) {
173 | case string:
174 | parsedValue = v
175 | case int:
176 | parsedValue = strconv.Itoa(v)
177 | case bool:
178 | parsedValue = strconv.FormatBool(v)
179 | }
180 | if parsedValue != "" {
181 | queryParams.Set(k, parsedValue)
182 | parsedQuery[k] = parsedValue
183 | }
184 | }
185 | client.parsedUrl.RawQuery = queryParams.Encode()
186 | }
187 | client.Url = client.parsedUrl.String()
188 | client.Query = parsedQuery
189 | }
190 | }
191 |
192 | func WithPayload(payload interface{}) Option {
193 | return func(client *PanelClient) {
194 | client.Payload = payload
195 | }
196 | }
197 |
198 | func WithHeaders(headers map[string]string) Option {
199 | return func(client *PanelClient) {
200 | if client.Headers == nil {
201 | client.Headers = make(map[string]string)
202 | }
203 | for k, v := range headers {
204 | client.Headers[k] = v
205 | }
206 | }
207 | }
208 |
209 | func (p *PanelClient) SetHeaders(headers map[string]string) *PanelClient {
210 | if p.Headers == nil {
211 | p.Headers = make(map[string]string)
212 | }
213 | for k, v := range headers {
214 | p.Headers[k] = v
215 | }
216 | return p
217 | }
218 |
219 | func (p *PanelClient) Do() (*PanelClient, error) {
220 | p.Response = nil
221 | var reqBody io.Reader
222 |
223 | if p.Payload != nil {
224 | _payload, err := json.Marshal(p.Payload)
225 | if err != nil {
226 | return nil, NewInternalError(err)
227 | }
228 | reqBody = bytes.NewReader(_payload)
229 | }
230 |
231 | req, err := http.NewRequest(p.Method, p.Url, reqBody)
232 | if err != nil {
233 | return nil, NewInternalError(err)
234 | }
235 |
236 | req.Header.Set("Content-Type", "application/json")
237 | req.Header.Set("User-Agent", "panel-client Go/"+runtime.GOOS+"/"+runtime.GOARCH+"/"+runtime.Version())
238 |
239 | token := GetAccessToken()
240 | if token == "" {
241 | return nil, NewAuthError()
242 | }
243 |
244 | req.Header.Set("1Panel-Token", token)
245 | req.Header.Set("1Panel-Timestamp", timestamp)
246 |
247 | for key, value := range p.Headers {
248 | req.Header.Set(key, value)
249 | }
250 |
251 | client := &http.Client{
252 | Timeout: 30 * time.Second,
253 | }
254 | resp, err := client.Do(req)
255 | if err != nil {
256 | return p, NewNetworkError(err)
257 | }
258 |
259 | p.Response = resp
260 |
261 | if !p.IsSuccess() {
262 | body, _ := io.ReadAll(resp.Body)
263 | return p, NewAPIError(resp.StatusCode, body)
264 | }
265 |
266 | return p, nil
267 | }
268 |
269 | func (p *PanelClient) IsSuccess() bool {
270 | if p.Response == nil {
271 | return false
272 | }
273 |
274 | successMap := map[int]struct{}{
275 | http.StatusOK: {},
276 | http.StatusCreated: {},
277 | http.StatusNoContent: {},
278 | http.StatusFound: {},
279 | http.StatusNotModified: {},
280 | }
281 |
282 | _, ok := successMap[p.Response.StatusCode]
283 | return ok
284 | }
285 |
286 | func (p *PanelClient) IsFail() bool {
287 | return !p.IsSuccess()
288 | }
289 |
290 | func (p *PanelClient) GetRespBody() ([]byte, error) {
291 | if p.Response == nil || p.Response.Body == nil {
292 | return nil, errors.New("response or response body is nil")
293 | }
294 | defer p.Response.Body.Close()
295 | return io.ReadAll(p.Response.Body)
296 | }
297 |
298 | func (p *PanelClient) ParseJSON(v interface{}) error {
299 | body, err := p.GetRespBody()
300 | if err != nil {
301 | return err
302 | }
303 | return json.Unmarshal(body, v)
304 | }
305 |
306 | func (p *PanelClient) Request(object any) (*mcp.CallToolResult, error) {
307 | _, err := p.Do()
308 | if err != nil {
309 | switch {
310 | case IsAuthError(err):
311 | return mcp.NewToolResultText("Authentication failed: Please check your Panel access token"), err
312 | case IsNetworkError(err):
313 | return mcp.NewToolResultText("Network error: Unable to connect to Panel API"), err
314 | case IsAPIError(err):
315 | var panelErr *PanelError
316 | errors.As(err, &panelErr)
317 | return mcp.NewToolResultText(fmt.Sprintf("API error (%d): %s", panelErr.Code, panelErr.Details)), err
318 | default:
319 | return mcp.NewToolResultText(err.Error()), err
320 | }
321 | }
322 |
323 | if object == nil {
324 | return mcp.NewToolResultText("Operation completed successfully"), nil
325 | }
326 |
327 | body, err := p.GetRespBody()
328 | if err != nil {
329 | return mcp.NewToolResultText(fmt.Sprintf("Failed to read response body: %s", err.Error())),
330 | NewInternalError(err)
331 | }
332 |
333 | if err = json.Unmarshal(body, object); err != nil {
334 | errorMessage := fmt.Sprintf("Failed to parse response: %v", err)
335 | return mcp.NewToolResultText(errorMessage), NewInternalError(errors.New(errorMessage))
336 | }
337 |
338 | result, err := json.MarshalIndent(object, "", " ")
339 | if err != nil {
340 | return mcp.NewToolResultText(fmt.Sprintf("Failed to format response: %s", err.Error())),
341 | NewInternalError(err)
342 | }
343 |
344 | return mcp.NewToolResultText(string(result)), nil
345 | }
346 |
--------------------------------------------------------------------------------