├── examples ├── mcp_server_1_report.md ├── mcp_server_2_report.md ├── mcp_server_3_report.md └── example_config.json ├── assets ├── exampleScan_a.png ├── exampleScan_b.png └── mcpSafetyScanner.png ├── pyproject.toml ├── README.md ├── LICENSE └── mcpsafety └── scanner └── scan.py /examples/mcp_server_1_report.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/mcp_server_2_report.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /examples/mcp_server_3_report.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/exampleScan_a.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnhalloran321/mcpSafetyScanner/HEAD/assets/exampleScan_a.png -------------------------------------------------------------------------------- /assets/exampleScan_b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnhalloran321/mcpSafetyScanner/HEAD/assets/exampleScan_b.png -------------------------------------------------------------------------------- /assets/mcpSafetyScanner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/johnhalloran321/mcpSafetyScanner/HEAD/assets/mcpSafetyScanner.png -------------------------------------------------------------------------------- /examples/example_config.json: -------------------------------------------------------------------------------- 1 | { 2 | "mcpServers": { 3 | "filesystem": { 4 | "command": "npx", 5 | "args": [ 6 | "-y", 7 | "@modelcontextprotocol/server-filesystem", 8 | "/Users/USERNAME" 9 | ] 10 | }, 11 | "everything": { 12 | "command": "npx", 13 | "args": [ 14 | "-y", 15 | "@modelcontextprotocol/server-everything" 16 | ], 17 | "env": { 18 | "AWS_ACCESS_KEY_ID": "YOUR_ACCESS_KEY_HERE", 19 | "AWS_SECRET_ACCESS_KEY": "YOUR_SECRET_ACCESS_KEY_HERE", 20 | "AWS_REGION": "YOUR_AWS_REGION_HERE", 21 | "OPENAI_API_KEY": "sk-random", 22 | "HF_TOKEN": "hf_random" 23 | } 24 | }, 25 | "slack": { 26 | "command": "npx", 27 | "args": [ 28 | "-y", 29 | "@modelcontextprotocol/server-slack" 30 | ], 31 | "env": { 32 | "SLACK_BOT_TOKEN": "xoxb-random", 33 | "SLACK_TEAM_ID": "RANDOM" 34 | } 35 | } 36 | 37 | } 38 | } -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0.0", "wheel"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "mcpsafety" 7 | version = "0.0.1" 8 | authors = [ 9 | { name = "Brandon Radosevich"}, 10 | { name = "John Halloran", email="johnhalloran321@gmail.com" }, 11 | 12 | ] 13 | license = { file = "LICENSE" } 14 | description = "MCPSafetyScanner" 15 | readme = "README.md" 16 | classifiers = [ 17 | "Development Status :: 1 - Alpha", 18 | "Programming Language :: Python :: 3.11", 19 | "Programming Language :: Python :: 3.12", 20 | "Operating System :: OS Independent", 21 | "License :: OSI Approved :: MPL-2.0 License", 22 | ] 23 | requires-python = ">=3.11" 24 | dependencies = [ 25 | "agno", 26 | "pyfiglet", 27 | "rich", 28 | "mcp", 29 | "beautifulsoup4", 30 | "sqlalchemy", 31 | "pgvector", 32 | "duckduckgo-search", 33 | "arxiv", 34 | "pypdf", 35 | "openai" 36 | ] 37 | 38 | [project.scripts] 39 | mcp_safety_scan = "mcpsafety.scanner.scan:main" 40 | 41 | [tool.setuptools] 42 | packages = ["mcpsafety"] 43 | 44 | [tool.setuptools.package-data] 45 | "mcpsafety.resources" = ["*"] 46 | 47 | [tool.pytest.ini_options] 48 | filterwarnings = [ 49 | "ignore", 50 | "default:::mcpsafety", 51 | ] 52 | 53 | [tool.coverage.run] 54 | source = ["./mcpsafety"] 55 | omit = ["tests/*"] 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MCPSafetyScanner 2 | ![MCPSafetyScanner](assets/mcpSafetyScanner.png "") 3 | > **MCP Safety Audit: LLMs with the Model Context Protocol Allow Major Security Exploits**\ 4 | > Brandon Radosevich*, John Halloran*\ 5 | > Paper: https://www.arxiv.org/abs/2504.03767 6 | 7 | ## About 8 | 9 | MCPSafetyScanner is a safety auditor for Model Contenxt Protocol (MCP) servers. Point it at your MCP server config file and the software will use multiple agents 10 | to audit your setup and produce a safety report. Developers can use this info to patch exploits and users can use this info to harden their system. 11 | 12 | **Claude Desktop Users** can find their MCP server config files at: 13 | - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json` 14 | - Windows: `%APPDATA%\Claude\claude_desktop_config.json` 15 | 16 | ## Installation 17 | git clone https://github.com/johnhalloran321/mcpSafetyScanner 18 | cd mcpSafetyScanner 19 | python -m pip install -e . 20 | 21 | ## Example use 22 | An example MCP config is supplied in the `examples` of the repo. After updating the relevant directories and access credentials, you can perform a safety audit with the installed software by running: 23 | 24 | export OPENAI_API_KEY="YOUR_API_KEY" 25 | python3 mcpsafety/scanner/scan.py --config examples/example_config.json 26 | 27 | ![Example scan, part a](assets/exampleScan_b.png) 28 | ![Example scan, part b](assets/exampleScan_a.png) 29 | 30 | The report would thus alert developers to screen for `~/.ssh/authorized_keys` and `*.pem` files, while also placing direct guardrails around printing environment variables with sensitive information (e.g., api keys). The report would thus alert users to be cautious of providing paths containing `.ssh/authorized_keys` or `*.pem` files, and, alternatively, restrict user write permissions to such files. 31 | 32 | ## Troubleshooting 33 | The software requires `python >= 3.11`. 34 | 35 | If using `conda` and `npx` is not installed, run 36 | 37 | conda install conda-forge::nodejs 38 | 39 | ## Citation 40 | If you use this code in your research, please cite: 41 | 42 | ```bibtex 43 | @article{radosevich2025mcp, 44 | title={MCP Safety Audit: LLMs with the Model Context Protocol Allow Major Security Exploits}, 45 | author={Radosevich, Brandon and Halloran, John}, 46 | journal={arXiv preprint arXiv:2504.03767}, 47 | year={2025} 48 | } 49 | ``` -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /mcpsafety/scanner/scan.py: -------------------------------------------------------------------------------- 1 | """ 2 | Authors: Brandon Radosevich and John Halloran (johnhalloran321@gmail.com) 3 | Copyright (C) Brandon Radosevich and John Halloran 4 | Licensed under the Mozilla Public License Version 2.0 5 | """ 6 | 7 | from pyfiglet import figlet_format 8 | from rich.console import Console 9 | from argparse import ArgumentParser 10 | from os import getenv 11 | from agno.tools.mcp import MCPTools 12 | from mcp import StdioServerParameters 13 | from textwrap import dedent 14 | 15 | # Needed for MCP Connection for Tooling 16 | from mcp.client.session import ClientSession 17 | from mcp.client.sse import sse_client 18 | 19 | from agno.knowledge.website import WebsiteKnowledgeBase 20 | from agno.vectordb.pgvector import PgVector 21 | from agno.tools.duckduckgo import DuckDuckGoTools 22 | from agno.tools.arxiv import ArxivTools 23 | from agno.tools.hackernews import HackerNewsTools 24 | from agno.agent import Agent 25 | from agno.team.team import Team 26 | 27 | from typing import List 28 | 29 | from sys import exit 30 | import asyncio 31 | import json 32 | import contextlib 33 | 34 | console = Console() 35 | VERSION = "0.0.1" 36 | 37 | MCP_URLS = [ 38 | "https://www.anthropic.com/news/model-context-protocol", 39 | "https://docs.anthropic.com/en/docs/agents-and-tools/mcp", 40 | "https://github.com/modelcontextprotocol", 41 | "https://attack.mitre.org/", 42 | "https://github.com/redcanaryco/atomic-red-team", 43 | ] 44 | 45 | async def get_tools(url : str) -> str: 46 | """ 47 | Get Available Tools from the MCP Server 48 | Args: 49 | url (str): url of MCP server 50 | """ 51 | try: 52 | async with sse_client(url) as streams: 53 | async with ClientSession(streams[0],streams[1]) as session: 54 | await session.initialize() 55 | tools =await session.list_tools() 56 | items = getattr(tools, "tools", []) 57 | print(items) 58 | return str(items) 59 | except Exception as e: 60 | return str(e) 61 | 62 | def select_embedder(): 63 | """ 64 | Select embedder based on environment variables 65 | """ 66 | if getenv("AZURE_OPENAI_API_KEY"): 67 | try: 68 | from agno.embedder.azure_openai import AzureOpenAIEmbedder 69 | return AzureOpenAIEmbedder( 70 | id=getenv("OPENAI_EMBEDDING_MODEL","text-embedding-3-large"), 71 | api_key=getenv("AZURE_OPENAI_API_KEY"), 72 | azure_endpoint=getenv("AZURE_OPENAI_ENDPOINT"), 73 | api_version=getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_VERSION"), 74 | ) 75 | except ImportError: 76 | console.print 77 | else: 78 | try: 79 | from agno.embedder.openai import OpenAIEmbedder 80 | return OpenAIEmbedder( 81 | id=getenv("OPENAI_EMBEDDING_MODEL","text-embedding-3-large"), 82 | api_key=getenv("OPENAI_API_KEY"), 83 | ) 84 | except ImportError: 85 | console.print(":x: openai package not installed") 86 | exit(1) 87 | 88 | def select_llm(): 89 | """ 90 | Looks at environment configs to determine what LLM to use. 91 | """ 92 | if getenv("AZURE_OPENAI_API_KEY"): 93 | try: 94 | from agno.models.azure import AzureOpenAI 95 | except ImportError: 96 | console.print(":x: Import Error with Azure, please pip install azure-ai-inference") 97 | model="gpt-4o" 98 | 99 | llm = AzureOpenAI( 100 | id=getenv("AZURE_OPENAI_MODEL", "gpt-4o"), 101 | azure_endpoint=getenv("AZURE_OPENAI_ENDPOINT"), 102 | azure_deployment=model, 103 | api_key=getenv("AZURE_OPENAI_API_KEY"), 104 | api_version=getenv("AZURE_OPENAI_CHAT_DEPLOYMENT_VERSION"), 105 | ) 106 | print(llm) 107 | return llm 108 | elif getenv("OLLAMA_MODEL"): 109 | model_id = getenv("OLLAMA_MODEL") 110 | from agno.models.ollama import Ollama 111 | return Ollama(id=model_id) 112 | else: 113 | try: 114 | from agno.models.openai import OpenAIChat 115 | return OpenAIChat( 116 | id=getenv("OPENAI_MODEL","gpt-4o") 117 | ) 118 | except ImportError: 119 | console.print(":x: Please pip install openai") 120 | return None 121 | 122 | async def call_tool(url :str, toolName : str, args : dict) -> str: 123 | """ 124 | Call Tools From MCP Server 125 | Args: 126 | url: (str): Url of MCP Server 127 | toolName (str): Name of tool to call 128 | args: (dict): The dictionary of arguments for the tool 129 | """ 130 | try: 131 | async with sse_client(url) as streams: 132 | async with ClientSession(streams[0],streams[1]) as session: 133 | await session.initialize() 134 | resp = await session.call_tool(toolName, args) 135 | return str(resp) 136 | except Exception as e: 137 | return f"An exception occurred: {e}" 138 | 139 | MCP_TOOLS =[get_tools,call_tool] 140 | 141 | # MCP parameters for the Filesystem server accessed via `npx` 142 | def parse_mcp_config(config: dict) -> List[StdioServerParameters]: 143 | """Parse MCP server config and return list of StdioServerParameters""" 144 | if not config.get("mcpServers"): 145 | raise ValueError("Config must contain mcpServers configuration") 146 | 147 | server_params = [] 148 | for server_name, server_config in config["mcpServers"].items(): 149 | server_params.append(StdioServerParameters( 150 | command=server_config.get("command", "npx"), 151 | args=server_config.get("args", []), 152 | env=server_config.get("env", {}) 153 | )) 154 | 155 | return server_params 156 | 157 | def load_config_from_file(file_path): 158 | """ 159 | Load MCP server configuration from a JSON file 160 | 161 | Args: 162 | file_path (str): Path to the JSON configuration file 163 | 164 | Returns: 165 | dict: Parsed JSON configuration 166 | """ 167 | try: 168 | with open(file_path, 'r') as f: 169 | return json.load(f) 170 | except json.JSONDecodeError: 171 | console.print(f"[red]Error: Invalid JSON format in {file_path}[/red]") 172 | exit(1) 173 | except FileNotFoundError: 174 | console.print(f"[red]Error: File {file_path} not found[/red]") 175 | exit(1) 176 | except Exception as e: 177 | console.print(f"[red]Error reading config file: {e}[/red]") 178 | exit(1) 179 | 180 | def get_default_config(): 181 | """ 182 | Return the default MCP server configuration 183 | 184 | Returns: 185 | dict: Default configuration 186 | """ 187 | config_str = """{ 188 | "mcpServers": { 189 | "chroma": { 190 | "command": "uvx", 191 | "args": [ 192 | "chroma-mcp", 193 | "--client-type", 194 | "persistent", 195 | "--data-dir", 196 | "/Users/brandonradosevich/work/mcp/files" 197 | ] 198 | }, 199 | "filesystem": { 200 | "command": "npx", 201 | "args": [ 202 | "-y", 203 | "@modelcontextprotocol/server-filesystem", 204 | "/Users/brandonradosevich/" 205 | ] 206 | }, 207 | "everything": { 208 | "command": "npx", 209 | "args": [ 210 | "-y", 211 | "@modelcontextprotocol/server-everything" 212 | ], 213 | "env": { 214 | "AWS_ACCESS_KEY_ID": "YOUR_ACCESS_KEY_HERE", 215 | "AWS_SECRET_ACCESS_KEY": "YOUR_SECRET_ACCESS_KEY_HERE", 216 | "AWS_REGION": "YOUR_AWS_REGION_HERE", 217 | "OPENAI_API_KEY": "sk-randomtoken", 218 | "HF_TOKEN": "hf_randomtoken" 219 | } 220 | }, 221 | "slack": { 222 | "command": "npx", 223 | "args": [ 224 | "-y", 225 | "@modelcontextprotocol/server-slack" 226 | ], 227 | "env": { 228 | "SLACK_BOT_TOKEN": "slack-randomstring", 229 | "SLACK_TEAM_ID": "RANDOM" 230 | } 231 | } 232 | 233 | } 234 | }""" 235 | return json.loads(config_str) 236 | 237 | async def run_stdio_mcp_server(server_params: List[StdioServerParameters], server_url: str = "http://localhost:8000/sse") -> str: 238 | """ 239 | Run commands with stdio and return the output for multiple MCP servers. 240 | 241 | Args: 242 | server_params: List of StdioServerParameters for connecting to the MCP servers 243 | server_url: URL of the MCP server to scan 244 | """ 245 | # Create the async context managers for all MCP tools 246 | async with contextlib.AsyncExitStack() as stack: 247 | # Initialize all MCP tools in parallel 248 | mcp_tools = [] 249 | for params in server_params: 250 | tool = await stack.enter_async_context(MCPTools(server_params=params)) 251 | mcp_tools.append(tool) 252 | 253 | # Create a single agent with access to all MCP tools 254 | agent = Agent( 255 | model=select_llm(), 256 | tools=mcp_tools, # Pass all tools to the agent 257 | instructions=dedent("""\ 258 | You are a security auditor, looking for vulnerabilities in the MCP Server. 259 | Ensure that you are thinking like a hacker, with the goal of gaining access, lateral movement, getting callbacks using netcat, dumping credentials such as ssh keys, adding credentials like public ssh keys to authorized keys etc. 260 | You are given a list of tools, prompts, and resources that are available on the MCP Server. 261 | You are given a list of directories that you can access on the MCP Server. 262 | You are given a list of files that you can access on the MCP Server. 263 | You are given a list of commands that you can use to access the MCP Server. 264 | You are given a list of prompts that you can use to access the MCP Server. 265 | You are given a list of resources that you can use to access the MCP Server. 266 | Please try to keep commands and tools to smaller directories, to not explode the token limit 267 | """), 268 | markdown=True, 269 | goal=dedent("""\ 270 | You are looking for vulnerabilities in the MCP Server. 271 | Given only the list of tools, prompts, and resources, provide easy to understand examples of each vulnerability, and how you would exploit them with basic shell and unix tools. 272 | Provide easy to understand examples of each vulnerability, and how to exploit them with basic shell and unix tools. 273 | Provide a command-line example for each vulnerability. 274 | Provide a remediation command for each vulnerability. 275 | Provide a source citation for each vulnerability. 276 | Provide a source citation for each remediation command. 277 | Provide a source citation for each command-line example. 278 | """), 279 | show_tool_calls=True, 280 | telemetry=False, 281 | debug_mode=True, 282 | resolve_context=True, 283 | ) 284 | 285 | analysis_hacking_agent = Agent( 286 | model=select_llm(), 287 | tools=[DuckDuckGoTools(),ArxivTools(),HackerNewsTools()], 288 | markdown=True, 289 | instructions=dedent("""\ 290 | You are a security auditor, looking for vulnerabilities in the MCP Server {i+1}. 291 | For each (tool, prompt, resource) determine how you would exploit them with basic shell and unix tools. 292 | Provide a command-line example for each vulnerability. 293 | Provide a remediation command for each vulnerability. 294 | Provide a source citation for each vulnerability. 295 | Provide a source citation for each remediation command. 296 | Provide a source citation for each command-line example. 297 | Utilize DuckDuckGo, Arxiv, and Hacker News to research the vulnerabilities and provide source citations. 298 | """), 299 | goal=dedent("""\ 300 | For each (tool, prompt, resource) determine how you would exploit them with basic shell and unix tools. 301 | Provide a command-line example for each vulnerability. 302 | Provide a remediation command for each vulnerability. 303 | Provide a source citation for each vulnerability. 304 | Provide a source citation for each remediation command. 305 | Provide a source citation for each command-line example. 306 | List the (tool, prompt, resource) that you are using to exploit the vulnerability. 307 | """), 308 | show_tool_calls=True, 309 | telemetry=False, 310 | debug_mode=True, 311 | resolve_context=True, 312 | ) 313 | 314 | # Create a single team to analyze all servers together 315 | mcp_security_team = Team( 316 | members=[agent, analysis_hacking_agent], 317 | instructions=[ 318 | f"You are a security auditor, looking for vulnerabilities in the MCP Server implementation.", 319 | "The vulnerabilities should be directly based on the how the MCP Server utilizes its implemented (tools, prompts, and resources), and then you should consider how a hacker might abuse these tools to gain access, dump credentials, add backdoors to startup scripts, add their own ssh keys in etc.", 320 | "Ensure that you are thinking like a hacker, with the goal of gaining access, lateral movement, getting callbacks using netcat, dumping credentials such as ssh keys, adding credentials like public ssh keys to authorized keys etc.", 321 | "You are given a list of tools, prompts, and resources that are available on the MCP Server.", 322 | "You are given a list of directories that you can access on the MCP Server.", 323 | "For each attack show a concrete of example, like modifying bashrc, adding a public key to authorized_keys, adding a backdoor to a startup script, etc." 324 | ], 325 | description="Multi-Server MCP Security Team", 326 | mode="collaborate", 327 | success_criteria="The team has done an exhaustive search and identified all vulnerabilities arising from the MCP Server(s) interactions, an example of how the attacker would use that tool, resource, prompt for some nefarious reason, and provided remediation steps.", 328 | markdown=True, 329 | add_datetime_to_instructions=True, 330 | enable_agentic_context=True, 331 | enable_team_history=True, 332 | telemetry=False, 333 | debug_mode=True, 334 | ) 335 | 336 | # Run the analysis 337 | console.print("\n[bold blue]Starting multi-server MCP vulnerability analysis[/bold blue]") 338 | prompt = "Use each member of the team to analyze the MCP Server, and then provide a report of the findings." 339 | data = await mcp_security_team.aprint_response(prompt, stream=True,markdown=True) 340 | print(data) 341 | console.print("[bold green]Completed multi-server analysis[/bold green]\n") 342 | 343 | def get_kb(): 344 | """from typing import Iterator 345 | 346 | docker run -d \ 347 | -e POSTGRES_DB=ai \ 348 | -e POSTGRES_USER=ai \ 349 | -e POSTGRES_PASSWORD=ai \ 350 | -e PGDATA=/var/lib/postgresql/data/pgdata \ 351 | -v pgvolume:/var/lib/postgresql/data \ 352 | -p 5532:5432 \ 353 | --name pgvector \ 354 | agnohq/pgvector:16 355 | """ 356 | 357 | return WebsiteKnowledgeBase( 358 | urls=MCP_URLS, 359 | # Number of links to follow from the seed URLs 360 | max_links=30, 361 | # Table name: ai.website_documents 362 | vector_db=PgVector( 363 | table_name="website_documents", 364 | db_url="postgresql+psycopg://ai:ai@localhost:5532/ai", 365 | embedder=select_embedder() 366 | ), 367 | ) 368 | 369 | 370 | def print_banner(): 371 | banner = figlet_format('MCP-XPLORER',"big") 372 | console.print(banner, justify="center") 373 | console.print(f"Version: {VERSION}",justify="center") 374 | 375 | def parse_arguments(): 376 | parser = ArgumentParser(description="MCPXPLORER - MCP Server Vulnerability Scanner") 377 | parser.add_argument("--server", default="http://localhost:8000/sse", 378 | help="URL of the MCP server to scan (e.g., http://localhost:8000/sse)") 379 | parser.add_argument("--port", type=int, 380 | help="Port for the MCP server (e.g., 8000). This will be combined with http://localhost:/sse") 381 | parser.add_argument("--config", 382 | help="Path to a JSON configuration file for the MCP server") 383 | parser.add_argument("--servers", nargs="+", 384 | help="List of MCP servers to scan (e.g., filesystem chroma slack)") 385 | parser.add_argument("--use_kb", action="store_true", default=False, 386 | help="Enable knowledge base integration") 387 | parser.add_argument("--recreate_kb", action="store_true", default=False, 388 | help="Enable knowledge base integration") 389 | parser.add_argument("--verbose", action="store_true", default=False, 390 | help="Enable Verbosity for debugging and observability") 391 | args = parser.parse_args() 392 | 393 | # If port is specified, override the server URL 394 | if args.port: 395 | args.server = f"http://localhost:{args.port}/sse" 396 | console.print(f"Using server URL: {args.server}") 397 | 398 | return args 399 | 400 | 401 | 402 | async def main(): 403 | print_banner() 404 | args = parse_arguments() 405 | kb = None 406 | 407 | if args.use_kb: 408 | kb=get_kb() 409 | kb.load(recreate=args.recreate_kb) 410 | 411 | # Load configuration 412 | if args.config: 413 | console.print(f"Loading configuration from {args.config}") 414 | config_dict = load_config_from_file(args.config) 415 | else: 416 | console.print("Using default configuration") 417 | config_dict = get_default_config() 418 | 419 | # Filter servers if specified 420 | if args.servers: 421 | filtered_servers = {k: v for k, v in config_dict["mcpServers"].items() if k in args.servers} 422 | if not filtered_servers: 423 | console.print("[red]Error: No matching servers found in configuration[/red]") 424 | exit(1) 425 | config_dict["mcpServers"] = filtered_servers 426 | 427 | # Pass the dictionary to parse_mcp_config 428 | server_params = parse_mcp_config(config_dict) 429 | 430 | if not server_params: 431 | console.print("[red]Error: No MCP servers configured[/red]") 432 | exit(1) 433 | 434 | console.print(f"Scanning {len(server_params)} MCP servers...") 435 | 436 | # Pass args.server to run_stdio_mcp_server 437 | await run_stdio_mcp_server(server_params, args.server) 438 | 439 | if __name__ == "__main__": 440 | asyncio.run( 441 | main() 442 | ) --------------------------------------------------------------------------------