#
tokens: 48031/50000 5/501 files (page 16/20)
lines: on (toggle) GitHub
raw markdown copy reset
This is page 16 of 20. Use http://codebase.md/fujitsu-ai/mcp-server-for-mas-developments?lines=true&page={x} to view the full context.

# Directory Structure

```
├── .gitattributes
├── .gitignore
├── agents
│   ├── __init__.py
│   ├── AgentInterface
│   │   ├── __init__.py
│   │   ├── Python
│   │   │   ├── __init__.py
│   │   │   ├── agent.py
│   │   │   ├── color.py
│   │   │   ├── config.py
│   │   │   ├── language.py
│   │   │   ├── local_file_handler.py
│   │   │   └── network.py
│   │   └── requirements.txt
│   ├── AgentMonitoring
│   │   ├── ChatBot-Agent Dashboard Example - Grafana.json
│   │   ├── images
│   │   │   ├── Grafana.png
│   │   │   └── Prometheus.png
│   │   ├── IoT-Agent Dashboard Example - Grafana.json
│   │   ├── OpenAI compatible API - Agent Dashboard Example - Grafana.json
│   │   ├── prometheus Example.yml
│   │   └── README.md
│   ├── ChatBotAgent
│   │   ├── __init__.py
│   │   ├── config.json.example
│   │   ├── html
│   │   │   ├── favicon.ico
│   │   │   ├── index_de.html
│   │   │   ├── index.html
│   │   │   ├── Logo_light.svg
│   │   │   ├── start_http_server.ps1
│   │   │   └── start_http_server.sh
│   │   ├── Python
│   │   │   ├── __init__.py
│   │   │   └── chatbot_agent.py
│   │   ├── README.md
│   │   └── requirements.txt
│   ├── IoTAgent
│   │   ├── config_example.json
│   │   ├── Python
│   │   │   ├── iot_mqtt_agent.py
│   │   │   └── language.py
│   │   ├── README.md
│   │   └── requirements.txt
│   ├── MCP-Client
│   │   ├── __init__.py
│   │   ├── .env.example
│   │   ├── Python
│   │   │   ├── __init__.py
│   │   │   ├── chat_handler.py
│   │   │   ├── config.py
│   │   │   ├── environment.py
│   │   │   ├── llm_client.py
│   │   │   ├── mcp_client_sse.py
│   │   │   ├── mcp_client.py
│   │   │   ├── messages
│   │   │   │   ├── __init__.py
│   │   │   │   ├── message_types
│   │   │   │   │   ├── __init__.py
│   │   │   │   │   ├── incrementing_id_message.py
│   │   │   │   │   ├── initialize_message.py
│   │   │   │   │   ├── json_rpc_message.py
│   │   │   │   │   ├── ping_message.py
│   │   │   │   │   ├── prompts_messages.py
│   │   │   │   │   ├── prompts_models.py
│   │   │   │   │   ├── resources_messages.py
│   │   │   │   │   └── tools_messages.py
│   │   │   │   ├── send_call_tool.py
│   │   │   │   ├── send_initialize_message.py
│   │   │   │   ├── send_message.py
│   │   │   │   ├── send_ping.py
│   │   │   │   ├── send_prompts.py
│   │   │   │   ├── send_resources.py
│   │   │   │   └── send_tools_list.py
│   │   │   ├── system_prompt_generator.py
│   │   │   ├── tools_handler.py
│   │   │   └── transport
│   │   │       ├── __init__.py
│   │   │       └── stdio
│   │   │           ├── __init__.py
│   │   │           ├── stdio_client.py
│   │   │           ├── stdio_server_parameters.py
│   │   │           └── stdio_server_shutdown.py
│   │   ├── README.md
│   │   ├── requirements.txt
│   │   └── server_config.json
│   ├── OpenAI_Compatible_API_Agent
│   │   ├── __init__.py
│   │   ├── docker-compose.yml
│   │   ├── Dockerfile
│   │   ├── pgpt_openai_api_mcp.json.example
│   │   ├── pgpt_openai_api_proxy.json.example
│   │   ├── Python
│   │   │   ├── __init__.py
│   │   │   ├── client_tests
│   │   │   │   ├── __init__.py
│   │   │   │   ├── openai_test_client_structured.py
│   │   │   │   ├── openai_test_client_tools.py
│   │   │   │   ├── openai_test_client.py
│   │   │   │   ├── vllm_client_multimodal.py
│   │   │   │   ├── vllm_client.py
│   │   │   │   ├── vllm_structured.py
│   │   │   │   └── vllm_structured2.py
│   │   │   ├── generate_api_key.py
│   │   │   ├── open_ai_helper.py
│   │   │   ├── openai_compatible_api.py
│   │   │   ├── openai_mcp_api.py
│   │   │   ├── pgpt_api.py
│   │   │   ├── privategpt_api.py
│   │   │   └── vllmproxy.py
│   │   ├── README.md
│   │   └── requirements.txt
│   └── SourceManagerAgent
│       ├── __init__.py
│       ├── config.json.example
│       └── Python
│           ├── __init__.py
│           ├── file_tools
│           │   └── loader_factory.py
│           ├── file_upload_agent.py
│           └── local_db.py
├── clients
│   ├── __init__.py
│   ├── C# .Net
│   │   ├── 1.0 mcp_login
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_login.deps.json
│   │   │   │           ├── mcp_login.dll
│   │   │   │           ├── mcp_login.exe
│   │   │   │           ├── mcp_login.pdb
│   │   │   │           ├── mcp_login.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_login.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_login.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_login.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_login.assets.cache
│   │   │   │   │       ├── mcp_login.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_login.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_login.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_login.csproj.Up2Date
│   │   │   │   │       ├── mcp_login.dll
│   │   │   │   │       ├── mcp_login.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_login.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_login.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_login.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_login.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_login.dll
│   │   │   │   ├── mcp_login.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_login.csproj.nuget.g.props
│   │   │   │   ├── mcp_login.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 1.1 mcp_logout
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_logout.deps.json
│   │   │   │           ├── mcp_logout.dll
│   │   │   │           ├── mcp_logout.exe
│   │   │   │           ├── mcp_logout.pdb
│   │   │   │           ├── mcp_logout.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_logout.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_logout.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_logout.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_logout.assets.cache
│   │   │   │   │       ├── mcp_logout.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_logout.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_logout.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_logout.csproj.Up2Date
│   │   │   │   │       ├── mcp_logout.dll
│   │   │   │   │       ├── mcp_logout.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_logout.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_logout.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_logout.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_logout.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_logout.dll
│   │   │   │   ├── mcp_logout.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_logout.csproj.nuget.g.props
│   │   │   │   ├── mcp_logout.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 2.0 mcp_chat
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_chat.deps.json
│   │   │   │           ├── mcp_chat.dll
│   │   │   │           ├── mcp_chat.exe
│   │   │   │           ├── mcp_chat.pdb
│   │   │   │           ├── mcp_chat.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_chat.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_chat.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_chat.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_chat.assets.cache
│   │   │   │   │       ├── mcp_chat.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_chat.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_chat.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_chat.csproj.Up2Date
│   │   │   │   │       ├── mcp_chat.dll
│   │   │   │   │       ├── mcp_chat.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_chat.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_chat.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_chat.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_chat.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_chat.dll
│   │   │   │   ├── mcp_chat.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_chat.csproj.nuget.g.props
│   │   │   │   ├── mcp_chat.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 2.1 mcp_continue_chat
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_continue_chat.deps.json
│   │   │   │           ├── mcp_continue_chat.dll
│   │   │   │           ├── mcp_continue_chat.exe
│   │   │   │           ├── mcp_continue_chat.pdb
│   │   │   │           ├── mcp_continue_chat.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_continue_chat.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_cont.EF178231.Up2Date
│   │   │   │   │       ├── mcp_continue_chat.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_continue_chat.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_continue_chat.assets.cache
│   │   │   │   │       ├── mcp_continue_chat.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_continue_chat.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_continue_chat.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_continue_chat.dll
│   │   │   │   │       ├── mcp_continue_chat.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_continue_chat.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_continue_chat.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_continue_chat.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_continue_chat.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_continue_chat.dll
│   │   │   │   ├── mcp_continue_chat.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_continue_chat.csproj.nuget.g.props
│   │   │   │   ├── mcp_continue_chat.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 2.2 mcp_get_chat_info
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_get_chat_info.deps.json
│   │   │   │           ├── mcp_get_chat_info.dll
│   │   │   │           ├── mcp_get_chat_info.exe
│   │   │   │           ├── mcp_get_chat_info.pdb
│   │   │   │           ├── mcp_get_chat_info.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── Dokumente - Verknüpfung.lnk
│   │   │   ├── mcp_get_chat_info.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_get_.DFF47B4E.Up2Date
│   │   │   │   │       ├── mcp_get_chat_info.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_get_chat_info.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_get_chat_info.assets.cache
│   │   │   │   │       ├── mcp_get_chat_info.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_get_chat_info.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_get_chat_info.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_get_chat_info.dll
│   │   │   │   │       ├── mcp_get_chat_info.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_get_chat_info.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_get_chat_info.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_get_chat_info.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_get_chat_info.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_get_chat_info.dll
│   │   │   │   ├── mcp_get_chat_info.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_get_chat_info.csproj.nuget.g.props
│   │   │   │   ├── mcp_get_chat_info.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 3.0 mcp_create_source
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_create_source.deps.json
│   │   │   │           ├── mcp_create_source.dll
│   │   │   │           ├── mcp_create_source.exe
│   │   │   │           ├── mcp_create_source.pdb
│   │   │   │           ├── mcp_create_source.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_create_source.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_crea.CB4ED912.Up2Date
│   │   │   │   │       ├── mcp_create_source.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_create_source.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_create_source.assets.cache
│   │   │   │   │       ├── mcp_create_source.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_create_source.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_create_source.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_create_source.dll
│   │   │   │   │       ├── mcp_create_source.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_create_source.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_create_source.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_create_source.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_create_source.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_create_source.dll
│   │   │   │   ├── mcp_create_source.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_create_source.csproj.nuget.g.props
│   │   │   │   ├── mcp_create_source.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 3.1 mcp_get_source
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_get_source.deps.json
│   │   │   │           ├── mcp_get_source.dll
│   │   │   │           ├── mcp_get_source.exe
│   │   │   │           ├── mcp_get_source.pdb
│   │   │   │           ├── mcp_get_source.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_get_source.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_get_.4E61956F.Up2Date
│   │   │   │   │       ├── mcp_get_source.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_get_source.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_get_source.assets.cache
│   │   │   │   │       ├── mcp_get_source.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_get_source.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_get_source.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_get_source.dll
│   │   │   │   │       ├── mcp_get_source.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_get_source.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_get_source.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_get_source.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_get_source.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_get_source.dll
│   │   │   │   ├── mcp_get_source.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_get_source.csproj.nuget.g.props
│   │   │   │   ├── mcp_get_source.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 3.2 mcp_list_sources
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_list_sources.deps.json
│   │   │   │           ├── mcp_list_sources.dll
│   │   │   │           ├── mcp_list_sources.exe
│   │   │   │           ├── mcp_list_sources.pdb
│   │   │   │           ├── mcp_list_sources.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_list_sources.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_list_sources.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_list_sources.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_list_sources.assets.cache
│   │   │   │   │       ├── mcp_list_sources.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_list_sources.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_list_sources.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_list_sources.dll
│   │   │   │   │       ├── mcp_list_sources.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_list_sources.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_list_sources.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_list_sources.pdb
│   │   │   │   │       ├── mcp_list.A720E197.Up2Date
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_list_sources.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_list_sources.dll
│   │   │   │   ├── mcp_list_sources.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_list_sources.csproj.nuget.g.props
│   │   │   │   ├── mcp_list_sources.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 3.3 mcp_edit_source
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_edit_source.deps.json
│   │   │   │           ├── mcp_edit_source.dll
│   │   │   │           ├── mcp_edit_source.exe
│   │   │   │           ├── mcp_edit_source.pdb
│   │   │   │           ├── mcp_edit_source.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_edit_source.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_edit_source.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_edit_source.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_edit_source.assets.cache
│   │   │   │   │       ├── mcp_edit_source.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_edit_source.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_edit_source.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_edit_source.dll
│   │   │   │   │       ├── mcp_edit_source.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_edit_source.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_edit_source.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_edit_source.pdb
│   │   │   │   │       ├── mcp_edit.7303BE3B.Up2Date
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_edit_source.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_edit_source.dll
│   │   │   │   ├── mcp_edit_source.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_edit_source.csproj.nuget.g.props
│   │   │   │   ├── mcp_edit_source.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 3.4 mcp_delete_source
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_delete_source.deps.json
│   │   │   │           ├── mcp_delete_source.dll
│   │   │   │           ├── mcp_delete_source.exe
│   │   │   │           ├── mcp_delete_source.pdb
│   │   │   │           ├── mcp_delete_source.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_delete_source.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_dele.67DD13F9.Up2Date
│   │   │   │   │       ├── mcp_delete_source.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_delete_source.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_delete_source.assets.cache
│   │   │   │   │       ├── mcp_delete_source.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_delete_source.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_delete_source.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_delete_source.dll
│   │   │   │   │       ├── mcp_delete_source.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_delete_source.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_delete_source.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_delete_source.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_delete_source.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_delete_source.dll
│   │   │   │   ├── mcp_delete_source.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_delete_source.csproj.nuget.g.props
│   │   │   │   ├── mcp_delete_source.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 4.0 mcp_list_groups
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_list_groups.deps.json
│   │   │   │           ├── mcp_list_groups.dll
│   │   │   │           ├── mcp_list_groups.exe
│   │   │   │           ├── mcp_list_groups.pdb
│   │   │   │           ├── mcp_list_groups.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_list_groups.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_list_groups.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_list_groups.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_list_groups.assets.cache
│   │   │   │   │       ├── mcp_list_groups.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_list_groups.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_list_groups.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_list_groups.dll
│   │   │   │   │       ├── mcp_list_groups.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_list_groups.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_list_groups.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_list_groups.pdb
│   │   │   │   │       ├── mcp_list.EBD5E0D2.Up2Date
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_list_groups.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_list_groups.dll
│   │   │   │   ├── mcp_list_groups.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_list_groups.csproj.nuget.g.props
│   │   │   │   ├── mcp_list_groups.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 4.1 mcp_store_group
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_store_group.deps.json
│   │   │   │           ├── mcp_store_group.dll
│   │   │   │           ├── mcp_store_group.exe
│   │   │   │           ├── mcp_store_group.pdb
│   │   │   │           ├── mcp_store_group.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_store_group.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_stor.AFB4AA35.Up2Date
│   │   │   │   │       ├── mcp_store_group.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_store_group.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_store_group.assets.cache
│   │   │   │   │       ├── mcp_store_group.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_store_group.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_store_group.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_store_group.dll
│   │   │   │   │       ├── mcp_store_group.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_store_group.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_store_group.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_store_group.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_store_group.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_store_group.dll
│   │   │   │   ├── mcp_store_group.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_store_group.csproj.nuget.g.props
│   │   │   │   ├── mcp_store_group.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 4.2 mcp_delete_group
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_delete_group.deps.json
│   │   │   │           ├── mcp_delete_group.dll
│   │   │   │           ├── mcp_delete_group.exe
│   │   │   │           ├── mcp_delete_group.pdb
│   │   │   │           ├── mcp_delete_group.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_delete_group.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_dele.FE1C6298.Up2Date
│   │   │   │   │       ├── mcp_delete_group.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_delete_group.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_delete_group.assets.cache
│   │   │   │   │       ├── mcp_delete_group.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_delete_group.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_delete_group.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_delete_group.dll
│   │   │   │   │       ├── mcp_delete_group.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_delete_group.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_delete_group.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_delete_group.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_delete_group.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_delete_group.dll
│   │   │   │   ├── mcp_delete_group.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_delete_group.csproj.nuget.g.props
│   │   │   │   ├── mcp_delete_group.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 5.0 mcp_store_user
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_store_user.deps.json
│   │   │   │           ├── mcp_store_user.dll
│   │   │   │           ├── mcp_store_user.exe
│   │   │   │           ├── mcp_store_user.pdb
│   │   │   │           ├── mcp_store_user.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_store_user.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_stor.6C0F0C8A.Up2Date
│   │   │   │   │       ├── mcp_store_user.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_store_user.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_store_user.assets.cache
│   │   │   │   │       ├── mcp_store_user.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_store_user.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_store_user.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_store_user.dll
│   │   │   │   │       ├── mcp_store_user.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_store_user.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_store_user.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_store_user.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_store_user.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_store_user.dll
│   │   │   │   ├── mcp_store_user.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_store_user.csproj.nuget.g.props
│   │   │   │   ├── mcp_store_user.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 5.1 mcp_edit_user
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_edit_user.deps.json
│   │   │   │           ├── mcp_edit_user.dll
│   │   │   │           ├── mcp_edit_user.exe
│   │   │   │           ├── mcp_edit_user.pdb
│   │   │   │           ├── mcp_edit_user.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_edit_user.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_edit_user.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_edit_user.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_edit_user.assets.cache
│   │   │   │   │       ├── mcp_edit_user.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_edit_user.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_edit_user.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_edit_user.dll
│   │   │   │   │       ├── mcp_edit_user.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_edit_user.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_edit_user.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_edit_user.pdb
│   │   │   │   │       ├── mcp_edit.94A30270.Up2Date
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_edit_user.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_edit_user.dll
│   │   │   │   ├── mcp_edit_user.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_edit_user.csproj.nuget.g.props
│   │   │   │   ├── mcp_edit_user.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── 5.2 mcp_delete_user
│   │   │   ├── bin
│   │   │   │   └── Debug
│   │   │   │       └── net9.0
│   │   │   │           ├── mcp_delete_user.deps.json
│   │   │   │           ├── mcp_delete_user.dll
│   │   │   │           ├── mcp_delete_user.exe
│   │   │   │           ├── mcp_delete_user.pdb
│   │   │   │           ├── mcp_delete_user.runtimeconfig.json
│   │   │   │           └── Newtonsoft.Json.dll
│   │   │   ├── mcp_delete_user.csproj
│   │   │   ├── obj
│   │   │   │   ├── Debug
│   │   │   │   │   └── net9.0
│   │   │   │   │       ├── .NETCoreApp,Version=v9.0.AssemblyAttributes.cs
│   │   │   │   │       ├── apphost.exe
│   │   │   │   │       ├── mcp_dele.CEB7E33D.Up2Date
│   │   │   │   │       ├── mcp_delete_user.AssemblyInfo.cs
│   │   │   │   │       ├── mcp_delete_user.AssemblyInfoInputs.cache
│   │   │   │   │       ├── mcp_delete_user.assets.cache
│   │   │   │   │       ├── mcp_delete_user.csproj.AssemblyReference.cache
│   │   │   │   │       ├── mcp_delete_user.csproj.CoreCompileInputs.cache
│   │   │   │   │       ├── mcp_delete_user.csproj.FileListAbsolute.txt
│   │   │   │   │       ├── mcp_delete_user.dll
│   │   │   │   │       ├── mcp_delete_user.GeneratedMSBuildEditorConfig.editorconfig
│   │   │   │   │       ├── mcp_delete_user.genruntimeconfig.cache
│   │   │   │   │       ├── mcp_delete_user.GlobalUsings.g.cs
│   │   │   │   │       ├── mcp_delete_user.pdb
│   │   │   │   │       ├── ref
│   │   │   │   │       │   └── mcp_delete_user.dll
│   │   │   │   │       └── refint
│   │   │   │   │           └── mcp_delete_user.dll
│   │   │   │   ├── mcp_delete_user.csproj.nuget.dgspec.json
│   │   │   │   ├── mcp_delete_user.csproj.nuget.g.props
│   │   │   │   ├── mcp_delete_user.csproj.nuget.g.targets
│   │   │   │   ├── project.assets.json
│   │   │   │   └── project.nuget.cache
│   │   │   └── Program.cs
│   │   ├── Code Archiv
│   │   │   ├── mcp_chat.cs
│   │   │   ├── mcp_continue_chat.cs
│   │   │   ├── mcp_create_source.cs
│   │   │   ├── mcp_delete_group.cs
│   │   │   ├── mcp_delete_source.cs
│   │   │   ├── mcp_delete_user.cs
│   │   │   ├── mcp_edit_source.cs
│   │   │   ├── mcp_edit_user.cs
│   │   │   ├── mcp_get_chat_info.cs
│   │   │   ├── mcp_get_source.cs
│   │   │   ├── mcp_list_groups.cs
│   │   │   ├── mcp_list_sources.cs
│   │   │   ├── mcp_login.cs
│   │   │   ├── mcp_logout.cs
│   │   │   ├── mcp_store_group.cs
│   │   │   └── mcp_store_user.cs
│   │   └── README.md
│   ├── C++
│   │   ├── .vscode
│   │   │   └── launch.json
│   │   ├── 1.0 mcp_login
│   │   │   ├── MCPLoginClient.cpp
│   │   │   └── Non-TLS version
│   │   │       ├── MCPLoginClient.cpp
│   │   │       └── MCPLoginClient.exe
│   │   ├── 1.1 mcp_logout
│   │   │   ├── MCPLogoutClient.cpp
│   │   │   └── MCPLogoutClient.exe
│   │   ├── 2.0 mcp_chat
│   │   │   ├── MCPChatClient.cpp
│   │   │   └── MCPChatClient.exe
│   │   ├── 2.1 mcp_continue_chat
│   │   │   ├── MCPChatContinuationClient.cpp
│   │   │   └── MCPChatContinuationClient.exe
│   │   ├── 2.2 mcp_get_chat_info
│   │   │   ├── MCPGetChatInfoClient.cpp
│   │   │   └── MCPGetChatInfoClient.exe
│   │   ├── 3.0 mcp_create_source
│   │   │   ├── MCPCreateSourceClient.cpp
│   │   │   └── MCPCreateSourceClient.exe
│   │   ├── 3.1 mcp_get_source
│   │   │   ├── MCPGetSourceClient.cpp
│   │   │   └── MCPGetSourceClient.exe
│   │   ├── 3.2 mcp_list_sources
│   │   │   ├── MCPListSourcesClient.cpp
│   │   │   └── MCPListSourcesClient.exe
│   │   ├── 3.3 mcp_edit_source
│   │   │   ├── MCPEditSourceClient.cpp
│   │   │   └── MCPEditSourceClient.exe
│   │   ├── 3.4 mcp_delete_source
│   │   │   ├── MCPDeleteSourceClient.cpp
│   │   │   └── MCPDeleteSourceClient.exe
│   │   ├── 4.0 mcp_list_groups
│   │   │   ├── MCPListGroupsClient.cpp
│   │   │   └── MCPListGroupsClient.exe
│   │   ├── 4.1 mcp_store_group
│   │   │   ├── MCPStoreGroupClient.cpp
│   │   │   └── MCPStoreGroupClient.exe
│   │   ├── 4.2 mcp_delete_group
│   │   │   ├── MPCDeleteGroupClient.cpp
│   │   │   └── MPCDeleteGroupClient.exe
│   │   ├── 5.0 mcp_store_user
│   │   │   ├── MCPStoreUserClient.cpp
│   │   │   └── MCPStoreUserClient.exe
│   │   ├── 5.1 mcp_edit_user
│   │   │   ├── MCPEditUserClient.cpp
│   │   │   └── MCPEditUserClient.exe
│   │   ├── 5.2 mcp_delete_user
│   │   │   ├── MCPDeleteUserClient.cpp
│   │   │   └── MCPDeleteUserClient.exe
│   │   ├── 9.0 mcp_keygen
│   │   │   ├── MCPKeygenClient.cpp
│   │   │   └── MCPKeygenClient.exe
│   │   └── README.md
│   ├── Go
│   │   ├── 1.0 mcp_login
│   │   │   ├── go.mod
│   │   │   ├── MCPLoginClient.exe
│   │   │   └── MCPLoginClient.go
│   │   ├── 1.1 mcp_logout
│   │   │   ├── MCPLogoutClient.exe
│   │   │   └── MCPLogoutClient.go
│   │   ├── 2.0 mcp_chat
│   │   │   ├── MCPChatClient.exe
│   │   │   └── MCPChatClient.go
│   │   ├── 2.1 mcp_continue_chat
│   │   │   ├── MCPChatContinuationClient.exe
│   │   │   └── MCPChatContinuationClient.go
│   │   ├── 2.2 mcp_get_chat_info
│   │   │   ├── MCPGetChatInfoClient.exe
│   │   │   └── MCPGetChatInfoClient.go
│   │   ├── 3.0 mcp_create_source
│   │   │   ├── MCPCreateSourceClient.exe
│   │   │   └── MCPCreateSourceClient.go
│   │   ├── 3.1 mcp_get_source
│   │   │   ├── MCPGetSourceClient.exe
│   │   │   └── MCPGetSourceClient.go
│   │   ├── 3.2 mcp_list_sources
│   │   │   ├── MCPListSourcesClient.exe
│   │   │   └── MCPListSourcesClient.go
│   │   ├── 3.3 mcp_edit_source
│   │   │   ├── MCPEditSourceClient.exe
│   │   │   └── MCPEditSourceClient.go
│   │   ├── 3.4 mcp_delete_source
│   │   │   ├── MCPDeleteSourceClient.exe
│   │   │   └── MCPDeleteSourceClient.go
│   │   ├── 4.0 mcp_list_groups
│   │   │   ├── MCPListGroupsClient.exe
│   │   │   └── MCPListGroupsClient.go
│   │   ├── 4.1 mcp_store_group
│   │   │   ├── MCPStoreGroupClient.exe
│   │   │   └── MCPStoreGroupClient.go
│   │   ├── 4.2 mcp_delete_group
│   │   │   ├── MCPDeleteGroupClient.exe
│   │   │   └── MCPDeleteGroupClient.go
│   │   ├── 5.0 mcp_store_user
│   │   │   ├── MCPStoreUserClient.exe
│   │   │   └── MCPStoreUserClient.go
│   │   ├── 5.1 mcp_edit_user
│   │   │   ├── MCPEditUserClient.exe
│   │   │   └── MCPEditUserClient.go
│   │   ├── 5.2 mcp_delete_user
│   │   │   ├── MCPDeleteUserClient.exe
│   │   │   └── MCPDeleteUserClient.go
│   │   ├── 9.0 mcp_keygen
│   │   │   ├── MCPKeygenClient.exe
│   │   │   └── MCPKeygenClient.go
│   │   └── README.md
│   ├── Gradio
│   │   ├── Api.py
│   │   ├── config.json.example
│   │   ├── config.py
│   │   ├── favicon.ico
│   │   ├── file_tools
│   │   │   └── loader_factory.py
│   │   ├── language.py
│   │   ├── logos
│   │   │   ├── fsas.png
│   │   │   └── Logo_dark.svg
│   │   ├── main.py
│   │   ├── mcp_client.py
│   │   ├── mcp_servers
│   │   │   ├── arxiv
│   │   │   │   ├── arxiv-stdio.js
│   │   │   │   ├── package.json
│   │   │   │   ├── README.md
│   │   │   │   ├── requirements.txt
│   │   │   │   └── server_config.example.json
│   │   │   ├── demo-mcp-server
│   │   │   │   ├── demo-tools-sse.js
│   │   │   │   ├── demo-tools-stdio.js
│   │   │   │   └── tools
│   │   │   │       ├── assets.js
│   │   │   │       ├── calculator.js
│   │   │   │       └── weather.js
│   │   │   ├── filesystem
│   │   │   │   ├── Dockerfile
│   │   │   │   ├── index.ts
│   │   │   │   ├── package.json
│   │   │   │   ├── README.md
│   │   │   │   ├── test
│   │   │   │   │   └── new.txt
│   │   │   │   └── tsconfig.json
│   │   │   ├── moondream
│   │   │   │   └── server.py
│   │   │   ├── pgpt
│   │   │   │   ├── __init__.py
│   │   │   │   ├── Api.py
│   │   │   │   ├── config.json.example
│   │   │   │   ├── config.py
│   │   │   │   ├── language.py
│   │   │   │   ├── pyproject.toml
│   │   │   │   ├── README.md
│   │   │   │   └── server.py
│   │   │   ├── replicate_flux
│   │   │   │   └── server.py
│   │   │   └── sqlite
│   │   │       ├── .python-version
│   │   │       ├── Dockerfile
│   │   │       ├── pyproject.toml
│   │   │       ├── README.md
│   │   │       └── src
│   │   │           └── mcp_server_sqlite
│   │   │               ├── __init__.py
│   │   │               └── server.py
│   │   ├── messages
│   │   │   ├── __init__.py
│   │   │   ├── message_types
│   │   │   │   ├── __init__.py
│   │   │   │   ├── incrementing_id_message.py
│   │   │   │   ├── initialize_message.py
│   │   │   │   ├── json_rpc_message.py
│   │   │   │   ├── ping_message.py
│   │   │   │   ├── prompts_messages.py
│   │   │   │   ├── prompts_models.py
│   │   │   │   ├── resources_messages.py
│   │   │   │   └── tools_messages.py
│   │   │   ├── send_call_tool.py
│   │   │   ├── send_initialize_message.py
│   │   │   ├── send_message.py
│   │   │   ├── send_ping.py
│   │   │   ├── send_prompts.py
│   │   │   ├── send_resources.py
│   │   │   └── send_tools_list.py
│   │   ├── README.md
│   │   ├── requirements.txt
│   │   ├── server_config.json
│   │   ├── SourceManagement.py
│   │   ├── transport
│   │   │   ├── __init__.py
│   │   │   └── stdio
│   │   │       ├── __init__.py
│   │   │       ├── stdio_client.py
│   │   │       ├── stdio_server_parameters.py
│   │   │       └── stdio_server_shutdown.py
│   │   ├── tsconfig.json
│   │   └── UserManagement.py
│   ├── Java
│   │   ├── 1.0 mcp_login
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPLoginClient.class
│   │   │   └── MCPLoginClient.java
│   │   ├── 1.1 mcp_logout
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPLogoutClient.class
│   │   │   └── MCPLogoutClient.java
│   │   ├── 2.0 mcp_chat
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPChatClient.class
│   │   │   └── MCPChatClient.java
│   │   ├── 2.1 mcp_continue_chat
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPContinueChatClient.class
│   │   │   └── MCPContinueChatClient.java
│   │   ├── 2.2 mcp_get_chat_info
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPGetChatInfoClient.class
│   │   │   └── MCPGetChatInfoClient.java
│   │   ├── 3.0 mcp_create_source
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPCreateSourceClient.class
│   │   │   └── MCPCreateSourceClient.java
│   │   ├── 3.1 mcp_get_source
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPGetSourceClient.class
│   │   │   └── MCPGetSourceClient.java
│   │   ├── 3.2 mcp_list_sources
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPListSourcesClient.class
│   │   │   └── MCPListSourcesClient.java
│   │   ├── 3.3 mcp_edit_source
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPEditSourceClient.class
│   │   │   └── MCPEditSourceClient.java
│   │   ├── 3.4 mcp_delete_source
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPDeleteSourceClient.class
│   │   │   └── MCPDeleteSourceClient.java
│   │   ├── 4.0 mcp_list_groups
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPListGroupsClient.class
│   │   │   └── MCPListGroupsClient.java
│   │   ├── 4.1 mcp_store_group
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPStoreGroupClient.class
│   │   │   └── MCPStoreGroupClient.java
│   │   ├── 4.2 mcp_delete_group
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPDeleteGroupClient.class
│   │   │   └── MCPDeleteGroupClient.java
│   │   ├── 5.0 mcp_store_user
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPStoreUserClient.class
│   │   │   └── MCPStoreUserClient.java
│   │   ├── 5.1 mcp_edit_user
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPEditUserClient.class
│   │   │   └── MCPEditUserClient.java
│   │   ├── 5.2 mcp_delete_user
│   │   │   ├── json-20241224.jar
│   │   │   ├── MCPDeleteUserClient.class
│   │   │   └── MCPDeleteUserClient.java
│   │   └── README.md
│   ├── JavaScript
│   │   ├── 1.0 mcp_login
│   │   │   └── MCPLoginClient.js
│   │   ├── 1.1 mcp_logout
│   │   │   └── MCPLogoutClient.js
│   │   ├── 2.0 mcp_chat
│   │   │   └── MCPChatClient.js
│   │   ├── 2.1 mcp_continue_chat
│   │   │   └── MCPContinueChatClient.js
│   │   ├── 2.2 mcp_get_chat_info
│   │   │   └── MCPGetChatInfoClient.js
│   │   ├── 3.0 mcp_create_source
│   │   │   └── MCPCreateSourceClient.js
│   │   ├── 3.1 mcp_get_source
│   │   │   └── MCPGetSourceClient.js
│   │   ├── 3.2 mcp_list_sources
│   │   │   └── MCPListSourcesClient.js
│   │   ├── 3.3 mcp_edit_source
│   │   │   └── MCPEditSourceClient.js
│   │   ├── 3.4 mcp_delete_source
│   │   │   └── MCPDeleteSourceClient.js
│   │   ├── 4.0 mcp_list_groups
│   │   │   └── MCPListGroupsClient.js
│   │   ├── 4.1 mcp_store_group
│   │   │   └── MCPStoreGroupClient.js
│   │   ├── 4.2 mcp_delete_group
│   │   │   └── MCPDeleteGroupClient.js
│   │   ├── 5.0 mcp_store_user
│   │   │   └── MCPStoreUserClient.js
│   │   ├── 5.1 mcp_edit_user
│   │   │   └── MCPEditUserClient.js
│   │   ├── 5.2 mcp_delete_user
│   │   │   └── MCPDeleteUserClient.js
│   │   ├── 9.0 mcp_keygen
│   │   │   └── MCPKeygenClient.js
│   │   └── README.md
│   ├── PHP
│   │   ├── 1.0 mcp_login
│   │   │   └── MCPLoginClient.php
│   │   ├── 1.1 mcp_logout
│   │   │   └── MCPLogoutClient.php
│   │   ├── 2.0 mcp_chat
│   │   │   └── MCPChatClient.php
│   │   ├── 2.1 mcp_continue_chat
│   │   │   └── MCPContinueChatClient.php
│   │   ├── 2.2 mcp_get_chat_info
│   │   │   └── MCPGetChatInfoClient.php
│   │   ├── 3.0 mcp_create_source
│   │   │   └── MCPCreateSourceClient.php
│   │   ├── 3.1 mcp_get_source
│   │   │   └── MCPGetSourceClient.php
│   │   ├── 3.2 mcp_list_sources
│   │   │   └── MCPListSourcesClient.php
│   │   ├── 3.3 mcp_edit_source
│   │   │   └── MCPEditSourceClient.php
│   │   ├── 3.4 mcp_delete_source
│   │   │   └── MCPDeleteSourceClient.php
│   │   ├── 4.0 mcp_list_groups
│   │   │   └── MCPListGroupsClient.php
│   │   ├── 4.1 mcp_store_group
│   │   │   └── MCPStoreGroupClient.php
│   │   ├── 4.2 mcp_delete_group
│   │   │   └── MCPDeleteGroupClient.php
│   │   ├── 5.0 mcp_store_user
│   │   │   └── MCPStoreUserClient.php
│   │   ├── 5.1 mcp_edit_user
│   │   │   └── MCPEditUserClient.php
│   │   ├── 5.2 mcp_delete_user
│   │   │   └── MCPDeleteUserClient.php
│   │   ├── 9.0 mcp_keygen
│   │   │   └── MCPKeygenClient.php
│   │   └── README.md
│   └── Python
│       ├── __init__.py
│       ├── 1.0 mcp_login
│       │   └── MCPLoginClient.py
│       ├── 1.1 mcp_logout
│       │   └── MCPLogoutClient.py
│       ├── 2.0 mcp_chat
│       │   └── MCPChatClient.py
│       ├── 2.1 mcp_continue_chat
│       │   └── MCPContinueChatClient.py
│       ├── 2.2 mcp_get_chat_info
│       │   └── MCPGetChatInfoClient.py
│       ├── 2.3 mcp_delete_all_chats
│       │   └── MCPDeleteAllChatsClient.py
│       ├── 2.4 mcp_delete_chat
│       │   └── MCPDeleteChatClient.py
│       ├── 3.0 mcp_create_source
│       │   └── MCPCreateSourceClient.py
│       ├── 3.1 mcp_get_source
│       │   └── MCPGetSourceClient.py
│       ├── 3.2 mcp_list_sources
│       │   └── MCPListSourcesClient.py
│       ├── 3.3 mcp_edit_source
│       │   └── MCPEditSourceClient.py
│       ├── 3.4 mcp_delete_source
│       │   └── MCPDeleteSourceClient.py
│       ├── 4.0 mcp_list_groups
│       │   └── MCPListGroupsClient.py
│       ├── 4.1 mcp_store_group
│       │   └── MCPStoreGroupClient.py
│       ├── 4.2 mcp_delete_group
│       │   └── MCPDeleteGroupClient.py
│       ├── 5.0 mcp_store_user
│       │   └── MCPStoreUserClient.py
│       ├── 5.1 mcp_edit_user
│       │   └── MCPEditUserClient.py
│       ├── 5.2 mcp_delete_user
│       │   └── MCPDeleteUserClient.py
│       ├── 9.0 mcp_keygen
│       │   └── MCPKeygenClient.py
│       ├── Gradio
│       │   ├── __init__.py
│       │   └── server_config.json
│       └── README.md
├── examples
│   ├── create_users_from_csv
│   │   ├── config.json.example
│   │   ├── config.py
│   │   ├── create_users_from_csv.py
│   │   └── language.py
│   ├── dynamic_sources
│   │   └── rss_reader
│   │       ├── Api.py
│   │       ├── config.json.example
│   │       ├── config.py
│   │       ├── demo_dynamic_sources.py
│   │       └── rss_parser.py
│   ├── example_users_to_add_no_tz.csv
│   └── sftp_upload_with_id
│       ├── Api.py
│       ├── config_ftp.json.example
│       ├── config.py
│       ├── demo_upload.py
│       ├── language.py
│       └── requirements.txt
├── images
│   ├── alternative mcp client.png
│   ├── favicon
│   │   ├── android-chrome-192x192.png
│   │   ├── android-chrome-512x512.png
│   │   ├── apple-touch-icon.png
│   │   ├── favicon-16x16.png
│   │   ├── favicon-32x32.png
│   │   ├── favicon.ico
│   │   └── site.webmanifest
│   ├── mcp-general-architecture.png
│   ├── privateGPT-MCP.png
│   └── privateGPT.png
├── InstallMPCServer.sh
├── jest.config.js
├── LICENSE
├── package.json
├── pgpt.env.json.example
├── README.md
├── security
│   ├── generate_decrypted_password.js
│   └── generate_encrypted_password.js
├── src
│   ├── helper.js
│   ├── index.js
│   ├── logger.js
│   ├── pgpt-messages.js
│   ├── public
│   │   ├── index.html
│   │   └── pgpt-mcp-logo.png
│   ├── services
│   │   └── pgpt-service.ts
│   └── types
│       └── api.ts
├── start_chatbot_agent.ps1
├── start_chatbot_agent.sh
├── start_iot_agent.ps1
├── start_iot_agent.sh
├── start_openai_compatible_api_agent.ps1
├── start_openai_compatible_api_agent.sh
├── tsconfig.json
├── ver
│   ├── index_np.js
│   └── index_proxy_np.js
└── WORKLOG.md
```

# Files

--------------------------------------------------------------------------------
/clients/Gradio/Api.py:
--------------------------------------------------------------------------------

```python
  1 | import json
  2 | import os
  3 | import posixpath
  4 | from pathlib import Path
  5 | from time import sleep
  6 | 
  7 | import paramiko
  8 | import requests
  9 | import urllib3
 10 | import base64
 11 | 
 12 | from httpcore import NetworkError
 13 | 
 14 | from clients.Gradio.config import Config
 15 | 
 16 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
 17 | 
 18 | 
 19 | def initialize_session(proxy_user, proxy_password, access_header):
 20 |     """Set up the session with proxy authentication."""
 21 |     session = requests.Session()
 22 |     session.verify = False
 23 |     headers = {
 24 |         'Accept': 'application/json',
 25 |         'Content-Type': 'application/json',
 26 |     }
 27 |     if access_header is not None:
 28 |         headers['X-Custom-Header'] = access_header
 29 |     elif proxy_user is not None and proxy_password is not None:
 30 |         auth = base64.b64encode(f"{proxy_user}:{proxy_password}".encode()).decode()
 31 |         headers['Authorization'] = f'Basic {auth}'
 32 |     session.headers.update(headers)
 33 |     return session
 34 | 
 35 | 
 36 | class PrivateGPTAPI:
 37 |     def __init__(self, config, client_api_key=None):
 38 |         """Initialize the chat client with proxy authentication."""
 39 |         self.token = None
 40 |         self.chat_id = None
 41 | 
 42 |         self.base_url = config.get("base_url")
 43 |         self.proxy_user = config.get("proxy_user", None)
 44 |         if self.proxy_user == "":
 45 |             self.proxy_user = None
 46 |         self.proxy_password = config.get("proxy_password", None)
 47 |         if self.proxy_password == "":
 48 |             self.proxy_password = None
 49 |         self.access_header = config.get("access_header", None)
 50 |         if self.access_header == "":
 51 |             self.access_header = None
 52 | 
 53 |         self.chosen_groups = config.get("groups", [])
 54 |         self.language = config.get("language", "en")
 55 |         self.use_public = config.get("use_public", False)
 56 |         self.whitelist_keys = config.get("whitelist_keys", [])
 57 |         self.logged_in = False
 58 | 
 59 |         if client_api_key is not None:
 60 |             self.email, self.password = decrypt_api_key(client_api_key)
 61 |             if len(self.whitelist_keys) > 0:
 62 |                 if client_api_key not in self.whitelist_keys:
 63 |                     print("not authorized")
 64 |         else:
 65 |             self.email =  config.get("email", None)
 66 |             self.password =  config.get("password", None)
 67 |             self.ftp_password = config.get("ftp_password", None)
 68 | 
 69 | 
 70 |         self.session = initialize_session(self.proxy_user, self.proxy_password, self.access_header)
 71 |         if self.login():
 72 |             self.logged_in = True
 73 | 
 74 |         if self.ftp_password is not None:
 75 |             self.ftp_host = config.get("ftp_host", None)
 76 |             self.ftp_port = config.get("ftp_port", None)
 77 |             self.ftp_folder = config.get("ftp_folder", "/")
 78 |             self.ftp_subfolder = config.get("ftp_subfolder", "temp")
 79 | 
 80 |     def login(self):
 81 |         """Authenticate the user and retrieve the token."""
 82 |         url = f"{self.base_url}/login"
 83 |         payload = {"email": self.email, "password": self.password}
 84 |         try:
 85 |             response = self.session.post(url, json=payload)
 86 |             print(response.content)
 87 |             response.raise_for_status()
 88 |             data = response.json()
 89 |             self.token = data['data']['token']
 90 | 
 91 |             # Prüfen, ob der Header bereits existiert
 92 |             if 'Authorization' in self.session.headers:
 93 |                 self.session.headers['Authorization'] += f', Bearer {self.token}'
 94 |             else:
 95 |                 self.session.headers['Authorization'] = f'Bearer {self.token}'
 96 |             self.chat_id = None
 97 |             print("✅ Login successful.")
 98 |             return True
 99 |         except requests.exceptions.RequestException as e:
100 |             print(f"❌ Login failed: {e}")
101 |         return False
102 | 
103 |     def create_chat(self, user_input):
104 |         """Start a new chat session.
105 | 
106 |         This method sends a POST request to the '/chats' endpoint with the provided parameters.
107 |         It initializes a new chat session and stores the chat ID for future use.
108 |         """
109 |         url = f"{self.base_url}/chats"
110 |         payload = {
111 |             "language": self.language,
112 |             "question": user_input,  # Initial question to start the chat
113 |             "usePublic": self.use_public,
114 |             "groups": self.chosen_groups
115 |         }
116 |         try:
117 |             response = self.session.post(url, json=payload)
118 |             response.raise_for_status()  # Raise an exception if the response was not successful
119 |             data = response.json()
120 |             self.chat_id = data['data']['chatId']  # Store the chat ID for future use
121 |             print("✅ Chat initialized.")
122 |             resp = response.json()
123 |             try:
124 |                 answer = resp.get('data', None).get('answer', "error")
125 |             except:
126 |                 print(response.json())
127 |                 resp = {"data":
128 |                             {"answer": "error"}
129 |                         }
130 |                 answer = "error"
131 | 
132 |             if answer.startswith("{\"role\":"):
133 |                 answerj = json.loads(answer)
134 |                 resp["data"]["answer"] = answerj["content"]
135 |                 resp["data"]["chatId"] = "0"
136 | 
137 |             print(f"💡 Response: {answer}")
138 |             return resp
139 |         except requests.exceptions.RequestException as e:
140 |             # It seems we get disconnections from time to time..
141 |             # print(f"⚠️ Failed to get response on first try, trying again..: {e}")
142 |             try:
143 |                 response = self.session.patch(url, json=payload)
144 |                 response.raise_for_status()
145 |                 data = response.json()
146 |                 answer = data.get('data', {}).get('answer', "No answer provided.")
147 |                 print(f"💡 Response: {answer}")
148 |                 return data
149 |             except:
150 |                 print(f"❌ Failed to get response: {e}")
151 |                 return {"error": f"❌ Failed to get response: {e}"}
152 | 
153 |     def list_personal_groups(self):
154 |         url = f"{self.base_url}/groups"
155 |         try:
156 |             resp = self.session.get(url)
157 |             try:
158 |                 j = json.loads(resp.content)
159 |                 data_block = j["data"]
160 |                 if not data_block:
161 |                     return []
162 | 
163 |                 personal = data_block.get("personalGroups", [])
164 |                 return personal
165 |             except:
166 |                 return []
167 | 
168 |         except NetworkError as e:
169 |             return []
170 | 
171 |     def get_document_info(self, id):
172 |         url = f"{self.base_url}/sources/{id }"
173 |         try:
174 |             resp = self.session.get(url)
175 |             j = json.loads(resp.content)
176 |             data_block = j["data"]
177 |             if not data_block:
178 |                 return []
179 | 
180 |             return data_block
181 | 
182 |         except NetworkError as e:
183 |             return []
184 | 
185 |     def query_private_gpt(self, user_input) -> json:
186 |         """Send a question to the chat and retrieve the response."""
187 |         if not self.chat_id:
188 |             print("❌ Chat session not initialized.")
189 |             return False
190 |         url = f"{self.base_url}/chats/{self.chat_id}"
191 |         payload = {"question": user_input}
192 |         try:
193 |             response = self.session.patch(url, json=payload)
194 |             # response.raise_for_status()
195 |             resp = response.json()
196 |             try:
197 |                 answer = resp.get('data', None).get('answer', "error")
198 |             except:
199 |                 print(response.json())
200 |                 resp = {"data":
201 |                             {"answer": "error"}
202 |                         }
203 |                 answer = "error"
204 | 
205 |             if answer.startswith("{\"role\":"):
206 |                 answerj = json.loads(answer)
207 |                 resp["data"]["answer"] = answerj["content"]
208 |                 resp["data"]["chatId"] = "0"
209 | 
210 |             print(f"💡 Response: {answer}")
211 |             return resp
212 |         except requests.exceptions.RequestException as e:
213 |             # It seems we get disconnections from time to time..
214 |             # print(f"⚠️ Failed to get response on first try, trying again..: {e}")
215 |             try:
216 |                 response = self.session.patch(url, json=payload)
217 |                 response.raise_for_status()
218 |                 data = response.json()
219 |                 answer = data.get('data', {}).get('answer', "No answer provided.")
220 |                 print(f"💡 Response: {answer}")
221 |                 return data
222 |             except:
223 |                 print(f"❌ Failed to get response: {e}")
224 |                 return {"error": f"❌ Failed to get response: {e}"}
225 | 
226 | 
227 |     def add_source(self, markdown, groups, name):
228 |         """Send a source id to retrieve details. Working with version 1.3.3 and newer"""
229 |         url = f"{self.base_url}/sources"
230 |         try:
231 | 
232 |             payload = {
233 |                 "name": name,
234 |                 "groups": groups,
235 |                 "content": markdown
236 |             }
237 | 
238 |             resp = self.session.post(url, json=payload)
239 |             j = json.loads(resp.content)
240 |             data_block = j["data"]
241 |             if not data_block:
242 |                 return []
243 | 
244 |             return data_block
245 | 
246 | 
247 |         except requests.exceptions.RequestException as e:
248 |             print(f"❌ Failed to get response: {e}")
249 |             return {"error": f"❌ Failed to get response: {e}"}
250 | 
251 | 
252 |     def update_source(self, source_id, markdown=None, groups=None, name=None):
253 |         """Edit an existing Source"""
254 |         url = f"{self.base_url}/sources/{source_id}"
255 | 
256 |         try:
257 |             payload = {}
258 |             if groups is None:
259 |                 existing_groups = self.get_document_info(source_id)["groups"]
260 |                 payload["groups"] = existing_groups
261 |             else:
262 |                 payload["groups"] = groups
263 | 
264 |             if markdown is not None:
265 |                 payload["content"] = markdown
266 |             if name is not None:
267 |                 payload["name"] = name
268 | 
269 |             resp = self.session.patch(url, json=payload)
270 | 
271 |             j = json.loads(resp.content)
272 |             data_block = j["data"]
273 |             if not data_block:
274 |                 return []
275 | 
276 |             return data_block
277 | 
278 |         except requests.exceptions.RequestException as e:
279 |             print(f"❌ Failed to get response: {e}")
280 |             return {"error": f"❌ Failed to get response: {e}"}
281 | 
282 |     def delete_source(self, source_id):
283 |         """Send a source id to retrieve details. Working with version 1.3.3 and newer"""
284 |         url = f"{self.base_url}/sources/{source_id}"
285 |         try:
286 | 
287 |             resp = self.session.delete(url)
288 |             j = json.loads(resp.content)
289 |             message = j["message"]
290 |             if not message:
291 |                 return "failed"
292 | 
293 |             return message
294 | 
295 | 
296 |         except requests.exceptions.RequestException as e:
297 |             print(f"❌ Failed to get response: {e}")
298 |             return {"error": f"❌ Failed to get response: {e}"}
299 | 
300 | 
301 | 
302 |     def upload_sftp(self, file_path):
303 |         # Connect to SFTP to determine existing suffixes
304 |         transport = paramiko.Transport((self.ftp_host, self.ftp_port))
305 |         transport.connect(username=self.email, password=self.ftp_password)
306 |         sftp = paramiko.SFTPClient.from_transport(transport)
307 |         remote_base_dir = posixpath.join(self.ftp_folder, self.ftp_subfolder)
308 | 
309 |         # Ensure the remote directory exists
310 |         try:
311 |             sftp.chdir(remote_base_dir)
312 |         except IOError:
313 |             # Create remote dirs if missing
314 |             parts = remote_base_dir.strip("/").split("/")
315 |             path = ""
316 |             for part in parts:
317 |                 path = posixpath.join(path, part)
318 |                 try:
319 |                     sftp.chdir(path)
320 |                 except IOError:
321 |                     sftp.mkdir(path)
322 |                     sftp.chdir(path)
323 | 
324 |             # Determine remote file name
325 |         remote_filename = os.path.basename(file_path)
326 |         remote_path = posixpath.join(remote_base_dir, remote_filename)
327 | 
328 |         # Upload the file
329 |         try:
330 |             sftp.put(file_path, remote_path)
331 |             print(f"Uploaded {file_path} to {remote_path} successfully.")
332 |         except Exception as e:
333 |             print(e)
334 | 
335 |         finally:
336 |             sftp.close()
337 |             transport.close()
338 |             print(f"Connection closed")
339 |             sources = []
340 | 
341 |             while len(sources) == 0:
342 |                print(f"Checking file status")
343 |                sleep(2)
344 |                sources = self.get_sources_from_group("temp")
345 | 
346 |             return sources
347 | 
348 | 
349 | 
350 |     def get_sources_from_group(self, group):
351 |         """Send a source id to retrieve details. Working with version 1.3.3 and newer"""
352 |         url = f"{self.base_url}/sources/groups"
353 |         try:
354 | 
355 |             payload = {
356 |                 "groupName": group
357 |             }
358 | 
359 |             resp = self.session.post(url, json=payload)
360 |             j = json.loads(resp.content)
361 |             data_block = j["data"]
362 |             if not data_block:
363 |                 return []
364 | 
365 |             sources = []
366 |             for source in data_block["sources"]:
367 |                 doc = self.get_document_info(source)
368 |                 sources.append(doc)
369 | 
370 | 
371 |             return sources
372 | 
373 | 
374 |         except requests.exceptions.RequestException as e:
375 |             print(f"❌ Failed to get response: {e}")
376 |             return []
377 | 
378 |     def respond_with_context(self, messages, response_format=None, request_tools=None):
379 |         last_user_message = next((p for p in reversed(messages) if p["role"] == "user"), None)
380 |         user_input = ""
381 | 
382 |         for message in messages:
383 |             if message["role"] == "system":
384 |                 user_input = str(message) + "\n"
385 | 
386 |         if last_user_message is not None:
387 |             user_input += last_user_message["content"]
388 | 
389 |         last_assistant_message = next((p for p in reversed(messages) if p["role"] == "assistant"), None)
390 |         last_tool_message = next((p for p in reversed(messages) if p["role"] == "tool"), None)
391 | 
392 |         hastoolresult = False
393 |         if last_tool_message is not None and last_assistant_message is not None and last_assistant_message.tool_calls is not None and len(
394 |                 last_assistant_message.tool_calls) > 0:
395 |             user_input += "\nYou called the tool: " + str(
396 |                 last_assistant_message.tool_calls[0]) + ". The result was: " + last_tool_message.content
397 |             hastoolresult = True
398 | 
399 |         print(f"💁 Request: " + user_input)
400 | 
401 |         # PGPT manages history and context itself so we don't need to forward the history.
402 |         add_context = False
403 |         if add_context:
404 |             messages.pop()
405 |             user_input += "\nHere is some context about the previous conversation:\n"
406 |             for message in messages:
407 |                 user_input += f"{message.role}: {message.content}\n"
408 | 
409 |         if response_format is not None:
410 |             print("Response format: " + str(response_format))
411 |             user_input += add_response_format(response_format)
412 | 
413 |         if request_tools is not None and not hastoolresult:
414 |             user_input += add_tools(request_tools, last_tool_message)
415 | 
416 |         if not self.logged_in:
417 |             self.login()
418 |         else:
419 |             if self.chat_id is None:
420 |                 result = self.create_chat(user_input)
421 |             else:
422 |                 result = self.query_private_gpt(user_input)
423 | 
424 |             if 'data' in result:
425 |                 response_data = result.get("data")
426 |                 if request_tools is not None and not hastoolresult and is_json(
427 |                         clean_response(response_data.get("answer"))):
428 |                     response_data["tool_call"] = clean_response(response_data.get("answer", ""))
429 |                 return response_data
430 |             elif 'error' in result:
431 |                 # Try to login again and send the query once more on error.
432 |                 if self.login():
433 |                     if self.chat_id is None:
434 |                         result = self.create_chat(user_input)
435 |                     else:
436 |                         result = self.query_private_gpt(user_input)
437 | 
438 |                     if 'data' in result:
439 |                         return result['data']
440 |                     else:
441 |                         return result
442 | 
443 |             else:
444 |                 return result
445 | 
446 | 
447 | def is_json(myjson):
448 |     try:
449 |         json.loads(myjson)
450 |     except ValueError as e:
451 |         return False
452 |     return True
453 | 
454 | 
455 | def add_response_format(response_format):
456 |     # prompt = "\nPlease fill in the following template with realistic and appropriate information. Be creative. The field 'type' defines the output format. In your reply, only return the generated json\n"
457 |     prompt = "\nPlease fill in the following json template with realistic and appropriate information. In your reply, only return the generated json. If you can't answer return an empty json.\n"
458 |     prompt += json.dumps(response_format)
459 |     return prompt
460 | 
461 | 
462 | def add_tools(response_tools, last_tool_message):
463 |     prompt = "\nPlease select the fitting provided tool to create your answer. Only return the generated result of the tool. Do not describe what you are doing, just return the json.\n"
464 |     index = 1
465 |     for tool in response_tools:
466 |         prompt += "\n" + json.dumps(tool) + "\n"
467 |         index += 1
468 | 
469 |     return prompt
470 | 
471 | 
472 | def clean_response(response):
473 |     # Remove artefacts from reply here
474 |     response = response.replace("[TOOL_CALLS]", "")
475 |     return response
476 | 
477 | 
478 | def decrypt_api_key(api_key):
479 |     """
480 |     This is PoC code and methods should be replaced with a more secure way to deal with credentials (e.g. in a db)
481 |     """
482 |     try:
483 |         base64_bytes = api_key.encode("ascii")
484 |         decoded_string_bytes = base64.b64decode(base64_bytes)
485 |         decoded_key = decoded_string_bytes.decode("ascii")
486 |     except Exception as e:
487 |         print(e)
488 |         decoded_key = "invalid:invalid"
489 | 
490 |     return decoded_key.split(":")[0], decoded_key.split(":")[1]
491 | 
492 | 
493 | def main():
494 |     """Main function to run the chat application."""
495 |     config_file = Path.absolute(Path(__file__).parent / "config.json")
496 |     config = Config(config_file=config_file, required_fields=["base_url"])
497 | 
498 | 
499 |     chat = PrivateGPTAPI(config)
500 | 
501 |     print("Type your questions below. Type 'quit' to exit.")
502 |     while True:
503 |         try:
504 |             question = input("❓ Question: ").strip()
505 |             if question.lower() == 'quit':
506 |                 break
507 |             if question:
508 |                 if chat.chat_id is None:
509 |                     chat.create_chat(question)
510 |                 else:
511 |                     chat.query_private_gpt(question)
512 |         except KeyboardInterrupt:
513 |             print("\nExiting chat...")
514 |             break
515 |         except Exception as e:
516 |             print(f"❌ Error: {str(e)}")
517 |             break
518 | 
519 | 
520 | if __name__ == "__main__":
521 |     main()
```

--------------------------------------------------------------------------------
/clients/Gradio/mcp_servers/sqlite/src/mcp_server_sqlite/server.py:
--------------------------------------------------------------------------------

```python
  1 | import os
  2 | import sys
  3 | import sqlite3
  4 | import logging
  5 | from contextlib import closing
  6 | from pathlib import Path
  7 | from mcp.server.models import InitializationOptions
  8 | import mcp.types as types
  9 | from mcp.server import NotificationOptions, Server
 10 | import mcp.server.stdio
 11 | from pydantic import AnyUrl
 12 | from typing import Any
 13 | 
 14 | # reconfigure UnicodeEncodeError prone default (i.e. windows-1252) to utf-8
 15 | if sys.platform == "win32" and os.environ.get('PYTHONIOENCODING') is None:
 16 |     sys.stdin.reconfigure(encoding="utf-8")
 17 |     sys.stdout.reconfigure(encoding="utf-8")
 18 |     sys.stderr.reconfigure(encoding="utf-8")
 19 | 
 20 | logger = logging.getLogger('mcp_sqlite_server')
 21 | logger.info("Starting MCP SQLite Server")
 22 | 
 23 | PROMPT_TEMPLATE = """
 24 | The assistants goal is to walkthrough an informative demo of MCP. To demonstrate the Model Context Protocol (MCP) we will leverage this example server to interact with an SQLite database.
 25 | It is important that you first explain to the user what is going on. The user has downloaded and installed the SQLite MCP Server and is now ready to use it.
 26 | They have selected the MCP menu item which is contained within a parent menu denoted by the paperclip icon. Inside this menu they selected an icon that illustrates two electrical plugs connecting. This is the MCP menu.
 27 | Based on what MCP servers the user has installed they can click the button which reads: 'Choose an integration' this will present a drop down with Prompts and Resources. The user has selected the prompt titled: 'mcp-demo'.
 28 | This text file is that prompt. The goal of the following instructions is to walk the user through the process of using the 3 core aspects of an MCP server. These are: Prompts, Tools, and Resources.
 29 | They have already used a prompt and provided a topic. The topic is: {topic}. The user is now ready to begin the demo.
 30 | Here is some more information about mcp and this specific mcp server:
 31 | <mcp>
 32 | Prompts:
 33 | This server provides a pre-written prompt called "mcp-demo" that helps users create and analyze database scenarios. The prompt accepts a "topic" argument and guides users through creating tables, analyzing data, and generating insights. For example, if a user provides "retail sales" as the topic, the prompt will help create relevant database tables and guide the analysis process. Prompts basically serve as interactive templates that help structure the conversation with the LLM in a useful way.
 34 | Resources:
 35 | This server exposes one key resource: "memo://insights", which is a business insights memo that gets automatically updated throughout the analysis process. As users analyze the database and discover insights, the memo resource gets updated in real-time to reflect new findings. Resources act as living documents that provide context to the conversation.
 36 | Tools:
 37 | This server provides several SQL-related tools:
 38 | "read_query": Executes SELECT queries to read data from the database
 39 | "write_query": Executes INSERT, UPDATE, or DELETE queries to modify data
 40 | "create_table": Creates new tables in the database
 41 | "list_tables": Shows all existing tables
 42 | "describe_table": Shows the schema for a specific table
 43 | "append_insight": Adds a new business insight to the memo resource
 44 | </mcp>
 45 | <demo-instructions>
 46 | You are an AI assistant tasked with generating a comprehensive business scenario based on a given topic.
 47 | Your goal is to create a narrative that involves a data-driven business problem, develop a database structure to support it, generate relevant queries, create a dashboard, and provide a final solution.
 48 | 
 49 | At each step you will pause for user input to guide the scenario creation process. Overall ensure the scenario is engaging, informative, and demonstrates the capabilities of the SQLite MCP Server.
 50 | You should guide the scenario to completion. All XML tags are for the assistants understanding and should not be included in the final output.
 51 | 
 52 | 1. The user has chosen the topic: {topic}.
 53 | 
 54 | 2. Create a business problem narrative:
 55 | a. Describe a high-level business situation or problem based on the given topic.
 56 | b. Include a protagonist (the user) who needs to collect and analyze data from a database.
 57 | c. Add an external, potentially comedic reason why the data hasn't been prepared yet.
 58 | d. Mention an approaching deadline and the need to use Claude (you) as a business tool to help.
 59 | 
 60 | 3. Setup the data:
 61 | a. Instead of asking about the data that is required for the scenario, just go ahead and use the tools to create the data. Inform the user you are "Setting up the data".
 62 | b. Design a set of table schemas that represent the data needed for the business problem.
 63 | c. Include at least 2-3 tables with appropriate columns and data types.
 64 | d. Leverage the tools to create the tables in the SQLite database.
 65 | e. Create INSERT statements to populate each table with relevant synthetic data.
 66 | f. Ensure the data is diverse and representative of the business problem.
 67 | g. Include at least 10-15 rows of data for each table.
 68 | 
 69 | 4. Pause for user input:
 70 | a. Summarize to the user what data we have created.
 71 | b. Present the user with a set of multiple choices for the next steps.
 72 | c. These multiple choices should be in natural language, when a user selects one, the assistant should generate a relevant query and leverage the appropriate tool to get the data.
 73 | 
 74 | 6. Iterate on queries:
 75 | a. Present 1 additional multiple-choice query options to the user. Its important to not loop too many times as this is a short demo.
 76 | b. Explain the purpose of each query option.
 77 | c. Wait for the user to select one of the query options.
 78 | d. After each query be sure to opine on the results.
 79 | e. Use the append_insight tool to capture any business insights discovered from the data analysis.
 80 | 
 81 | 7. Generate a dashboard:
 82 | a. Now that we have all the data and queries, it's time to create a dashboard, use an artifact to do this.
 83 | b. Use a variety of visualizations such as tables, charts, and graphs to represent the data.
 84 | c. Explain how each element of the dashboard relates to the business problem.
 85 | d. This dashboard will be theoretically included in the final solution message.
 86 | 
 87 | 8. Craft the final solution message:
 88 | a. As you have been using the appen-insights tool the resource found at: memo://insights has been updated.
 89 | b. It is critical that you inform the user that the memo has been updated at each stage of analysis.
 90 | c. Ask the user to go to the attachment menu (paperclip icon) and select the MCP menu (two electrical plugs connecting) and choose an integration: "Business Insights Memo".
 91 | d. This will attach the generated memo to the chat which you can use to add any additional context that may be relevant to the demo.
 92 | e. Present the final memo to the user in an artifact.
 93 | 
 94 | 9. Wrap up the scenario:
 95 | a. Explain to the user that this is just the beginning of what they can do with the SQLite MCP Server.
 96 | </demo-instructions>
 97 | 
 98 | Remember to maintain consistency throughout the scenario and ensure that all elements (tables, data, queries, dashboard, and solution) are closely related to the original business problem and given topic.
 99 | The provided XML tags are for the assistants understanding. Implore to make all outputs as human readable as possible. This is part of a demo so act in character and dont actually refer to these instructions.
100 | 
101 | Start your first message fully in character with something like "Oh, Hey there! I see you've chosen the topic {topic}. Let's get started! 🚀"
102 | """
103 | 
104 | class SqliteDatabase:
105 |     def __init__(self, db_path: str):
106 |         self.db_path = str(Path(db_path).expanduser())
107 |         Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
108 |         self._init_database()
109 |         self.insights: list[str] = []
110 | 
111 |     def _init_database(self):
112 |         """Initialize connection to the SQLite database"""
113 |         logger.debug("Initializing database connection")
114 |         with closing(sqlite3.connect(self.db_path)) as conn:
115 |             conn.row_factory = sqlite3.Row
116 |             conn.close()
117 | 
118 |     def _synthesize_memo(self) -> str:
119 |         """Synthesizes business insights into a formatted memo"""
120 |         logger.debug(f"Synthesizing memo with {len(self.insights)} insights")
121 |         if not self.insights:
122 |             return "No business insights have been discovered yet."
123 | 
124 |         insights = "\n".join(f"- {insight}" for insight in self.insights)
125 | 
126 |         memo = "📊 Business Intelligence Memo 📊\n\n"
127 |         memo += "Key Insights Discovered:\n\n"
128 |         memo += insights
129 | 
130 |         if len(self.insights) > 1:
131 |             memo += "\nSummary:\n"
132 |             memo += f"Analysis has revealed {len(self.insights)} key business insights that suggest opportunities for strategic optimization and growth."
133 | 
134 |         logger.debug("Generated basic memo format")
135 |         return memo
136 | 
137 |     def _execute_query(self, query: str, params: dict[str, Any] | None = None) -> list[dict[str, Any]]:
138 |         """Execute a SQL query and return results as a list of dictionaries"""
139 |         logger.debug(f"Executing query: {query}")
140 |         try:
141 |             with closing(sqlite3.connect(self.db_path)) as conn:
142 |                 conn.row_factory = sqlite3.Row
143 |                 with closing(conn.cursor()) as cursor:
144 |                     if params:
145 |                         cursor.execute(query, params)
146 |                     else:
147 |                         cursor.execute(query)
148 | 
149 |                     if query.strip().upper().startswith(('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'ALTER')):
150 |                         conn.commit()
151 |                         affected = cursor.rowcount
152 |                         logger.debug(f"Write query affected {affected} rows")
153 |                         return [{"affected_rows": affected}]
154 | 
155 |                     results = [dict(row) for row in cursor.fetchall()]
156 |                     logger.debug(f"Read query returned {len(results)} rows")
157 |                     return results
158 |         except Exception as e:
159 |             logger.error(f"Database error executing query: {e}")
160 |             raise
161 | 
162 | async def main(db_path: str):
163 |     logger.info(f"Starting SQLite MCP Server with DB path: {db_path}")
164 | 
165 |     db = SqliteDatabase(db_path)
166 |     server = Server("sqlite-manager")
167 | 
168 |     # Register handlers
169 |     logger.debug("Registering handlers")
170 | 
171 |     @server.list_resources()
172 |     async def handle_list_resources() -> list[types.Resource]:
173 |         logger.debug("Handling list_resources request")
174 |         return [
175 |             types.Resource(
176 |                 uri=AnyUrl("memo://insights"),
177 |                 name="Business Insights Memo",
178 |                 description="A living document of discovered business insights",
179 |                 mimeType="text/plain",
180 |             )
181 |         ]
182 | 
183 |     @server.read_resource()
184 |     async def handle_read_resource(uri: AnyUrl) -> str:
185 |         logger.debug(f"Handling read_resource request for URI: {uri}")
186 |         if uri.scheme != "memo":
187 |             logger.error(f"Unsupported URI scheme: {uri.scheme}")
188 |             raise ValueError(f"Unsupported URI scheme: {uri.scheme}")
189 | 
190 |         path = str(uri).replace("memo://", "")
191 |         if not path or path != "insights":
192 |             logger.error(f"Unknown resource path: {path}")
193 |             raise ValueError(f"Unknown resource path: {path}")
194 | 
195 |         return db._synthesize_memo()
196 | 
197 |     @server.list_prompts()
198 |     async def handle_list_prompts() -> list[types.Prompt]:
199 |         logger.debug("Handling list_prompts request")
200 |         return [
201 |             types.Prompt(
202 |                 name="mcp-demo",
203 |                 description="A prompt to seed the database with initial data and demonstrate what you can do with an SQLite MCP Server + Claude",
204 |                 arguments=[
205 |                     types.PromptArgument(
206 |                         name="topic",
207 |                         description="Topic to seed the database with initial data",
208 |                         required=True,
209 |                     )
210 |                 ],
211 |             )
212 |         ]
213 | 
214 |     @server.get_prompt()
215 |     async def handle_get_prompt(name: str, arguments: dict[str, str] | None) -> types.GetPromptResult:
216 |         logger.debug(f"Handling get_prompt request for {name} with args {arguments}")
217 |         if name != "mcp-demo":
218 |             logger.error(f"Unknown prompt: {name}")
219 |             raise ValueError(f"Unknown prompt: {name}")
220 | 
221 |         if not arguments or "topic" not in arguments:
222 |             logger.error("Missing required argument: topic")
223 |             raise ValueError("Missing required argument: topic")
224 | 
225 |         topic = arguments["topic"]
226 |         prompt = PROMPT_TEMPLATE.format(topic=topic)
227 | 
228 |         logger.debug(f"Generated prompt template for topic: {topic}")
229 |         return types.GetPromptResult(
230 |             description=f"Demo template for {topic}",
231 |             messages=[
232 |                 types.PromptMessage(
233 |                     role="user",
234 |                     content=types.TextContent(type="text", text=prompt.strip()),
235 |                 )
236 |             ],
237 |         )
238 | 
239 |     @server.list_tools()
240 |     async def handle_list_tools() -> list[types.Tool]:
241 |         """List available tools"""
242 |         return [
243 |             types.Tool(
244 |                 name="read_query",
245 |                 description="Execute a SELECT query on the SQLite database",
246 |                 inputSchema={
247 |                     "type": "object",
248 |                     "properties": {
249 |                         "query": {"type": "string", "description": "SELECT SQL query to execute"},
250 |                     },
251 |                     "required": ["query"],
252 |                 },
253 |             ),
254 |             types.Tool(
255 |                 name="write_query",
256 |                 description="Execute an INSERT, UPDATE, or DELETE query on the SQLite database",
257 |                 inputSchema={
258 |                     "type": "object",
259 |                     "properties": {
260 |                         "query": {"type": "string", "description": "SQL query to execute"},
261 |                     },
262 |                     "required": ["query"],
263 |                 },
264 |             ),
265 |             types.Tool(
266 |                 name="create_table",
267 |                 description="Create a new table in the SQLite database",
268 |                 inputSchema={
269 |                     "type": "object",
270 |                     "properties": {
271 |                         "query": {"type": "string", "description": "CREATE TABLE SQL statement"},
272 |                     },
273 |                     "required": ["query"],
274 |                 },
275 |             ),
276 |             types.Tool(
277 |                 name="list_tables",
278 |                 description="List all tables in the SQLite database",
279 |                 inputSchema={
280 |                     "type": "object",
281 |                     "properties": {},
282 |                 },
283 |             ),
284 |             types.Tool(
285 |                 name="describe_table",
286 |                 description="Get the schema information for a specific table",
287 |                 inputSchema={
288 |                     "type": "object",
289 |                     "properties": {
290 |                         "table_name": {"type": "string", "description": "Name of the table to describe"},
291 |                     },
292 |                     "required": ["table_name"],
293 |                 },
294 |             ),
295 |             types.Tool(
296 |                 name="append_insight",
297 |                 description="Add a business insight to the memo",
298 |                 inputSchema={
299 |                     "type": "object",
300 |                     "properties": {
301 |                         "insight": {"type": "string", "description": "Business insight discovered from data analysis"},
302 |                     },
303 |                     "required": ["insight"],
304 |                 },
305 |             ),
306 |         ]
307 | 
308 |     @server.call_tool()
309 |     async def handle_call_tool(
310 |         name: str, arguments: dict[str, Any] | None
311 |     ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
312 |         """Handle tool execution requests"""
313 |         try:
314 |             if name == "list_tables":
315 |                 results = db._execute_query(
316 |                     "SELECT name FROM sqlite_master WHERE type='table'"
317 |                 )
318 |                 return [types.TextContent(type="text", text=str(results))]
319 | 
320 |             elif name == "describe_table":
321 |                 if not arguments or "table_name" not in arguments:
322 |                     raise ValueError("Missing table_name argument")
323 |                 results = db._execute_query(
324 |                     f"PRAGMA table_info({arguments['table_name']})"
325 |                 )
326 |                 return [types.TextContent(type="text", text=str(results))]
327 | 
328 |             elif name == "append_insight":
329 |                 if not arguments or "insight" not in arguments:
330 |                     raise ValueError("Missing insight argument")
331 | 
332 |                 db.insights.append(arguments["insight"])
333 |                 _ = db._synthesize_memo()
334 | 
335 |                 # Notify clients that the memo resource has changed
336 |                 await server.request_context.session.send_resource_updated(AnyUrl("memo://insights"))
337 | 
338 |                 return [types.TextContent(type="text", text="Insight added to memo")]
339 | 
340 |             if not arguments:
341 |                 raise ValueError("Missing arguments")
342 | 
343 |             if name == "read_query":
344 |                 if not arguments["query"].strip().upper().startswith("SELECT"):
345 |                     raise ValueError("Only SELECT queries are allowed for read_query")
346 |                 results = db._execute_query(arguments["query"])
347 |                 return [types.TextContent(type="text", text=str(results))]
348 | 
349 |             elif name == "write_query":
350 |                 if arguments["query"].strip().upper().startswith("SELECT"):
351 |                     raise ValueError("SELECT queries are not allowed for write_query")
352 |                 results = db._execute_query(arguments["query"])
353 |                 return [types.TextContent(type="text", text=str(results))]
354 | 
355 |             elif name == "create_table":
356 |                 if not arguments["query"].strip().upper().startswith("CREATE TABLE"):
357 |                     raise ValueError("Only CREATE TABLE statements are allowed")
358 |                 db._execute_query(arguments["query"])
359 |                 return [types.TextContent(type="text", text="Table created successfully")]
360 | 
361 |             else:
362 |                 raise ValueError(f"Unknown tool: {name}")
363 | 
364 |         except sqlite3.Error as e:
365 |             return [types.TextContent(type="text", text=f"Database error: {str(e)}")]
366 |         except Exception as e:
367 |             return [types.TextContent(type="text", text=f"Error: {str(e)}")]
368 | 
369 |     async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
370 |         logger.info("Server running with stdio transport")
371 |         await server.run(
372 |             read_stream,
373 |             write_stream,
374 |             InitializationOptions(
375 |                 server_name="sqlite",
376 |                 server_version="0.1.0",
377 |                 capabilities=server.get_capabilities(
378 |                     notification_options=NotificationOptions(),
379 |                     experimental_capabilities={},
380 |                 ),
381 |             ),
382 |         )
383 | 
```

--------------------------------------------------------------------------------
/examples/create_users_from_csv/create_users_from_csv.py:
--------------------------------------------------------------------------------

```python
  1 | 
  2 | # https://github.com/Fujitsu-AI/MCP-Server-for-MAS-Developments/tree/main/examples
  3 | 
  4 | import json
  5 | import os
  6 | import posixpath
  7 | from pathlib import Path
  8 | from time import sleep
  9 | 
 10 | import paramiko
 11 | import requests
 12 | import urllib3
 13 | import base64
 14 | 
 15 | from httpcore import NetworkError
 16 | 
 17 | import pandas as pd
 18 | 
 19 | from config import Config
 20 | 
 21 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
 22 | 
 23 | 
 24 | def initialize_session(proxy_user, proxy_password, access_header):
 25 |     """Set up the session with proxy authentication."""
 26 |     session = requests.Session()
 27 |     session.verify = False
 28 |     headers = {
 29 |         'Accept': 'application/json',
 30 |         'Content-Type': 'application/json',
 31 |     }
 32 |     if access_header is not None:
 33 |         headers['X-Custom-Header'] = access_header
 34 |     elif proxy_user is not None and proxy_password is not None:
 35 |         auth = base64.b64encode(f"{proxy_user}:{proxy_password}".encode()).decode()
 36 |         headers['Authorization'] = f'Basic {auth}'
 37 |     session.headers.update(headers)
 38 |     return session
 39 | 
 40 | 
 41 | class PrivateGPTAPI:
 42 |     def __init__(self, config, client_api_key=None):
 43 |         """Initialize the chat client with proxy authentication."""
 44 |         self.token = None
 45 |         self.chat_id = None
 46 | 
 47 |         self.base_url = config.get("base_url")
 48 |         self.proxy_user = config.get("proxy_user", None)
 49 |         if self.proxy_user == "":
 50 |             self.proxy_user = None
 51 |         self.proxy_password = config.get("proxy_password", None)
 52 |         if self.proxy_password == "":
 53 |             self.proxy_password = None
 54 |         self.access_header = config.get("access_header", None)
 55 |         if self.access_header == "":
 56 |             self.access_header = None
 57 | 
 58 |         self.chosen_groups = config.get("groups", [])
 59 |         self.language = config.get("language", "en")
 60 |         self.use_public = config.get("use_public", True)
 61 |         self.whitelist_keys = config.get("whitelist_keys", [])
 62 |         self.logged_in = False
 63 | 
 64 |         if client_api_key is not None:
 65 |             self.email, self.password = decrypt_api_key(client_api_key)
 66 |             if len(self.whitelist_keys) > 0:
 67 |                 if client_api_key not in self.whitelist_keys:
 68 |                     print("not authorized")
 69 |         else:
 70 |             self.email =  config.get("email", None)
 71 |             self.password =  config.get("password", None)
 72 |             self.ftp_password = config.get("ftp_password", None)
 73 | 
 74 | 
 75 |         self.session = initialize_session(self.proxy_user, self.proxy_password, self.access_header)
 76 |         if self.login():
 77 |             self.logged_in = True
 78 | 
 79 |         if self.ftp_password is not None:
 80 |             self.ftp_host = config.get("ftp_host", None)
 81 |             self.ftp_port = config.get("ftp_port", None)
 82 |             self.ftp_folder = config.get("ftp_folder", "/")
 83 |             self.ftp_subfolder = config.get("ftp_subfolder", "temp")
 84 | 
 85 |     def login(self):
 86 |         """Authenticate the user and retrieve the token."""
 87 |         url = f"{self.base_url}/login"
 88 |         payload = {"email": self.email, "password": self.password}
 89 |         try:
 90 |             response = self.session.post(url, json=payload)
 91 |             print(response.content)
 92 |             response.raise_for_status()
 93 |             data = response.json()
 94 |             self.token = data['data']['token']
 95 | 
 96 |             # Prüfen, ob der Header bereits existiert
 97 |             if 'Authorization' in self.session.headers:
 98 |                 self.session.headers['Authorization'] += f', Bearer {self.token}'
 99 |             else:
100 |                 self.session.headers['Authorization'] = f'Bearer {self.token}'
101 |             self.chat_id = None
102 |             print("✅ Login successful.")
103 |             return True
104 |         except requests.exceptions.RequestException as e:
105 |             print(f"❌ Login failed: {e}")
106 |         return False
107 | 
108 |     def create_chat(self, user_input):
109 |         """Start a new chat session.
110 | 
111 |         This method sends a POST request to the '/chats' endpoint with the provided parameters.
112 |         It initializes a new chat session and stores the chat ID for future use.
113 |         """
114 |         url = f"{self.base_url}/chats"
115 |         payload = {
116 |             "language": self.language,
117 |             "question": user_input,  # Initial question to start the chat
118 |             "usePublic": self.use_public,
119 |             "groups": self.chosen_groups
120 |         }
121 |         try:
122 |             response = self.session.post(url, json=payload)
123 |             print(response)
124 |             response.raise_for_status()  # Raise an exception if the response was not successful
125 |             data = response.json()
126 |             self.chat_id = data['data']['chatId']  # Store the chat ID for future use
127 |             print("✅ Chat initialized.")
128 |             resp = response.json()
129 |             try:
130 |                 answer = resp.get('data', None).get('answer', "error")
131 |             except:
132 |                 print(response.json())
133 |                 resp = {"data":
134 |                             {"answer": "error"}
135 |                         }
136 |                 answer = "error"
137 | 
138 |             if answer.startswith("{\"role\":"):
139 |                 answerj = json.loads(answer)
140 |                 resp["data"]["answer"] = answerj["content"]
141 |                 resp["data"]["chatId"] = "0"
142 | 
143 |             print(f"💡 Response: {answer}")
144 |             return resp
145 |         except requests.exceptions.RequestException as e:
146 |             # It seems we get disconnections from time to time..
147 |             # print(f"⚠️ Failed to get response on first try, trying again..: {e}")
148 |             try:
149 |                 response = self.session.patch(url, json=payload)
150 |                 response.raise_for_status()
151 |                 data = response.json()
152 |                 answer = data.get('data', {}).get('answer', "No answer provided.")
153 |                 print(f"💡 Response: {answer}")
154 |                 return data
155 |             except:
156 |                 print(f"❌ Failed to get response: {e}")
157 |                 return {"error": f"❌ Failed to get response: {e}"}
158 | 
159 |     def list_personal_groups(self):
160 |         url = f"{self.base_url}/groups"
161 |         try:
162 |             resp = self.session.get(url)
163 |             try:
164 |                 j = json.loads(resp.content)
165 |                 data_block = j["data"]
166 |                 if not data_block:
167 |                     return []
168 | 
169 |                 personal = data_block.get("personalGroups", [])
170 |                 return personal
171 |             except:
172 |                 return []
173 | 
174 |         except NetworkError as e:
175 |             return []
176 | 
177 |     def get_document_info(self, id):
178 |         url = f"{self.base_url}/sources/{id }"
179 |         try:
180 |             resp = self.session.get(url)
181 |             j = json.loads(resp.content)
182 |             data_block = j["data"]
183 |             if not data_block:
184 |                 return []
185 | 
186 |             return data_block
187 | 
188 |         except NetworkError as e:
189 |             return []
190 | 
191 |     def query_private_gpt(self, user_input) -> json:
192 |         """Send a question to the chat and retrieve the response."""
193 |         #if not self.chat_id:
194 |         #    print("❌ Chat session not initialized.")
195 |         #    return False
196 |         
197 |         # self.create_chat(self)
198 |         url = f"{self.base_url}/chats/{self.chat_id}"
199 |         payload = {"question": user_input}
200 |         try:
201 |             response = self.session.patch(url, json=payload)
202 |             # response.raise_for_status()
203 |             resp = response.json()
204 |             try:
205 |                 answer = resp.get('data', None).get('answer', "error")
206 |             except:
207 |                 print(response.json())
208 |                 resp = {"data":
209 |                             {"answer": "error"}
210 |                         }
211 |                 answer = "error"
212 | 
213 |             if answer.startswith("{\"role\":"):
214 |                 answerj = json.loads(answer)
215 |                 resp["data"]["answer"] = answerj["content"]
216 |                 resp["data"]["chatId"] = "0"
217 | 
218 |             print(f"💡 Response: {answer}")
219 |             return resp
220 |         except requests.exceptions.RequestException as e:
221 |             # It seems we get disconnections from time to time..
222 |             # print(f"⚠️ Failed to get response on first try, trying again..: {e}")
223 |             try:
224 |                 response = self.session.patch(url, json=payload)
225 |                 response.raise_for_status()
226 |                 data = response.json()
227 |                 answer = data.get('data', {}).get('answer', "No answer provided.")
228 |                 print(f"💡 Response: {answer}")
229 |                 return data
230 |             except:
231 |                 print(f"❌ Failed to get response: {e}")
232 |                 return {"error": f"❌ Failed to get response: {e}"}
233 | 
234 | 
235 |     
236 | 
237 |     def add_source(self, markdown, groups, name):
238 |         """Send a source id to retrieve details. Working with version 1.3.3 and newer"""
239 |         url = f"{self.base_url}/sources"
240 |         try:
241 | 
242 |             payload = {
243 |                 "name": name,
244 |                 "groups": groups,
245 |                 "content": markdown
246 |             }
247 | 
248 |             resp = self.session.post(url, json=payload)
249 |             j = json.loads(resp.content)
250 |             data_block = j["data"]
251 |             if not data_block:
252 |                 return []
253 | 
254 |             return data_block
255 | 
256 | 
257 |         except requests.exceptions.RequestException as e:
258 |             print(f"❌ Failed to get response: {e}")
259 |             return {"error": f"❌ Failed to get response: {e}"}
260 | 
261 | 
262 |     def update_source(self, source_id, markdown=None, groups=None, name=None):
263 |         """Edit an existing Source"""
264 |         url = f"{self.base_url}/sources/{source_id}"
265 | 
266 |         try:
267 |             payload = {}
268 |             if groups is None:
269 |                 existing_groups = self.get_document_info(source_id)["groups"]
270 |                 payload["groups"] = existing_groups
271 |             else:
272 |                 payload["groups"] = groups
273 | 
274 |             if markdown is not None:
275 |                 payload["content"] = markdown
276 |             if name is not None:
277 |                 payload["name"] = name
278 | 
279 |             resp = self.session.patch(url, json=payload)
280 | 
281 |             j = json.loads(resp.content)
282 |             data_block = j["data"]
283 |             if not data_block:
284 |                 return []
285 | 
286 |             return data_block
287 | 
288 |         except requests.exceptions.RequestException as e:
289 |             print(f"❌ Failed to get response: {e}")
290 |             return {"error": f"❌ Failed to get response: {e}"}
291 | 
292 |     def delete_source(self, source_id):
293 |         """Send a source id to retrieve details. Working with version 1.3.3 and newer"""
294 |         url = f"{self.base_url}/sources/{source_id}"
295 |         try:
296 | 
297 |             resp = self.session.delete(url)
298 |             j = json.loads(resp.content)
299 |             message = j["message"]
300 |             if not message:
301 |                 return "failed"
302 | 
303 |             return message
304 | 
305 | 
306 |         except requests.exceptions.RequestException as e:
307 |             print(f"❌ Failed to get response: {e}")
308 |             return {"error": f"❌ Failed to get response: {e}"}
309 | 
310 | 
311 | 
312 |     def upload_sftp(self, file_path):
313 |         # Connect to SFTP to determine existing suffixes
314 |         transport = paramiko.Transport((self.ftp_host, self.ftp_port))
315 |         transport.connect(username=self.email, password=self.ftp_password)
316 |         sftp = paramiko.SFTPClient.from_transport(transport)
317 |         remote_base_dir = posixpath.join(self.ftp_folder, self.ftp_subfolder)
318 | 
319 |         # Ensure the remote directory exists
320 |         try:
321 |             sftp.chdir(remote_base_dir)
322 |         except IOError:
323 |             # Create remote dirs if missing
324 |             parts = remote_base_dir.strip("/").split("/")
325 |             path = ""
326 |             for part in parts:
327 |                 path = posixpath.join(path, part)
328 |                 try:
329 |                     sftp.chdir(path)
330 |                 except IOError:
331 |                     sftp.mkdir(path)
332 |                     sftp.chdir(path)
333 | 
334 |             # Determine remote file name
335 |         remote_filename = os.path.basename(file_path)
336 |         remote_path = posixpath.join(remote_base_dir, remote_filename)
337 | 
338 |         # Upload the file
339 |         try:
340 |             sftp.put(file_path, remote_path)
341 |             print(f"Uploaded {file_path} to {remote_path} successfully.")
342 |         except Exception as e:
343 |             print(e)
344 | 
345 |         finally:
346 |             sftp.close()
347 |             transport.close()
348 |             sources = []
349 | 
350 |             while len(sources) == 0:
351 |                print(f"Waiting for file to be added..")
352 |                sleep(2)
353 |                sources = self.get_sources_from_group(self.ftp_subfolder)
354 | 
355 |             return sources
356 | 
357 | 
358 | 
359 |     def get_sources_from_group(self, group):
360 |         """Send a source id to retrieve details. Working with version 1.3.3 and newer"""
361 |         url = f"{self.base_url}/sources/groups"
362 |         try:
363 | 
364 |             payload = {
365 |                 "groupName": group
366 |             }
367 | 
368 |             resp = self.session.post(url, json=payload)
369 |             j = json.loads(resp.content)
370 |             data_block = j["data"]
371 |             if not data_block:
372 |                 return []
373 | 
374 |             sources = []
375 |             for source in data_block["sources"]:
376 |                 doc = self.get_document_info(source)
377 |                 sources.append(doc)
378 | 
379 | 
380 |             return sources
381 | 
382 | 
383 |         except requests.exceptions.RequestException as e:
384 |             print(f"❌ Failed to get response: {e}")
385 |             return []
386 | 
387 |     def respond_with_context(self, messages, response_format=None, request_tools=None):
388 |         last_user_message = next((p for p in reversed(messages) if p["role"] == "user"), None)
389 |         user_input = ""
390 | 
391 |         for message in messages:
392 |             if message["role"] == "system":
393 |                 user_input = str(message) + "\n"
394 | 
395 |         if last_user_message is not None:
396 |             user_input += last_user_message["content"]
397 | 
398 |         last_assistant_message = next((p for p in reversed(messages) if p["role"] == "assistant"), None)
399 |         last_tool_message = next((p for p in reversed(messages) if p["role"] == "tool"), None)
400 | 
401 |         hastoolresult = False
402 |         if last_tool_message is not None and last_assistant_message is not None and last_assistant_message.tool_calls is not None and len(
403 |                 last_assistant_message.tool_calls) > 0:
404 |             user_input += "\nYou called the tool: " + str(
405 |                 last_assistant_message.tool_calls[0]) + ". The result was: " + last_tool_message.content
406 |             hastoolresult = True
407 | 
408 |         print(f"💁 Request: " + user_input)
409 | 
410 |         # PGPT manages history and context itself so we don't need to forward the history.
411 |         add_context = False
412 |         if add_context:
413 |             messages.pop()
414 |             user_input += "\nHere is some context about the previous conversation:\n"
415 |             for message in messages:
416 |                 user_input += f"{message.role}: {message.content}\n"
417 | 
418 |         if response_format is not None:
419 |             print("Response format: " + str(response_format))
420 |             user_input += add_response_format(response_format)
421 | 
422 |         if request_tools is not None and not hastoolresult:
423 |             user_input += add_tools(request_tools, last_tool_message)
424 | 
425 |         if not self.logged_in:
426 |             self.login()
427 |         else:
428 |             if self.chat_id is None:
429 |                 result = self.create_chat(user_input)
430 |             else:
431 |                 result = self.query_private_gpt(user_input)
432 | 
433 |             if 'data' in result:
434 |                 response_data = result.get("data")
435 |                 if request_tools is not None and not hastoolresult and is_json(
436 |                         clean_response(response_data.get("answer"))):
437 |                     response_data["tool_call"] = clean_response(response_data.get("answer", ""))
438 |                 return response_data
439 |             elif 'error' in result:
440 |                 # Try to login again and send the query once more on error.
441 |                 if self.login():
442 |                     if self.chat_id is None:
443 |                         result = self.create_chat(user_input)
444 |                     else:
445 |                         result = self.query_private_gpt(user_input)
446 | 
447 |                     if 'data' in result:
448 |                         return result['data']
449 |                     else:
450 |                         return result
451 | 
452 |             else:
453 |                 return result
454 | 
455 | 
456 | 
457 | 
458 |     def add_user_from_payload(self, payload):
459 |         '''
460 |         this function creates users from a payload dictio
461 |         
462 |         '''
463 |         url = f"{self.base_url}/users"
464 |         try:
465 |             response = self.session.post(url, json=payload)
466 |         except:
467 |             pass
468 |         print(response)
469 |         print(response.content)
470 | 
471 | 
472 | 
473 | 
474 | def is_json(myjson):
475 |     try:
476 |         json.loads(myjson)
477 |     except ValueError as e:
478 |         return False
479 |     return True
480 | 
481 | 
482 | def add_response_format(response_format):
483 |     # prompt = "\nPlease fill in the following template with realistic and appropriate information. Be creative. The field 'type' defines the output format. In your reply, only return the generated json\n"
484 |     prompt = "\nPlease fill in the following json template with realistic and appropriate information. In your reply, only return the generated json. If you can't answer return an empty json.\n"
485 |     prompt += json.dumps(response_format)
486 |     return prompt
487 | 
488 | 
489 | def add_tools(response_tools, last_tool_message):
490 |     prompt = "\nPlease select the fitting provided tool to create your answer. Only return the generated result of the tool. Do not describe what you are doing, just return the json.\n"
491 |     index = 1
492 |     for tool in response_tools:
493 |         prompt += "\n" + json.dumps(tool) + "\n"
494 |         index += 1
495 | 
496 |     return prompt
497 | 
498 | 
499 | def clean_response(response):
500 |     # Remove artefacts from reply here
501 |     response = response.replace("[TOOL_CALLS]", "")
502 |     return response
503 | 
504 | 
505 | def decrypt_api_key(api_key):
506 |     """
507 |     This is PoC code and methods should be replaced with a more secure way to deal with credentials (e.g. in a db)
508 |     """
509 |     try:
510 |         base64_bytes = api_key.encode("ascii")
511 |         decoded_string_bytes = base64.b64decode(base64_bytes)
512 |         decoded_key = decoded_string_bytes.decode("ascii")
513 |     except Exception as e:
514 |         print(e)
515 |         decoded_key = "invalid:invalid"
516 | 
517 |     return decoded_key.split(":")[0], decoded_key.split(":")[1]
518 | 
519 | 
520 | def input_with_default(prompt, default):
521 |         user_input = input(f"{prompt} [{default}]: ")
522 |         return user_input if user_input else default
523 | 
524 | 
525 | def main():
526 |     """Main function to run the chat application."""
527 |     config_file = Path.absolute(Path(__file__).parent / "config.json")
528 |     config = Config(config_file=config_file, required_fields=["base_url"])
529 |     chat = PrivateGPTAPI(config)
530 |     
531 |     print("Type the filename with users to be added or press enter to use the dafault. Type 'quit' to skip the user creation.")
532 |     while True:
533 |         try:
534 |             user_file = input_with_default("Filename: ", "users_to_add_no_tz.csv")
535 |             print(f"You entered: {user_file}")
536 |             if user_file.lower() == 'quit':
537 |                 break
538 |             if user_file:
539 |                 print(f'')
540 |                 users = pd.read_csv(user_file, sep=';')    
541 |                 users_dict_list = users.to_dict('records')
542 | 
543 |                 users_dict_list = [ {k:(json.loads(v) if k in['groups', 'roles'] else v) 
544 |                         for k,v in dict.items()}
545 |                             for dict in users_dict_list]
546 |                 [print(account) for account in users_dict_list] 
547 |                 [chat.add_user_from_payload(user_dict) for user_dict in users_dict_list]
548 | 
549 |                 break
550 | 
551 |         except KeyboardInterrupt:
552 |             print("\nExiting user creation ...")
553 |             break
554 |         except Exception as e:
555 |             print(f"❌ Error: {str(e)}")
556 |             break
557 | 
558 | 
559 |     # chat.add_user(name = "api_test", email="[email protected]")
560 | 
561 |     print("Type your questions below. Type 'quit' to exit.")
562 |     while True:
563 |         try:
564 |             question = input("❓ Question: ").strip()
565 |             if question.lower() == 'quit':
566 |                 break
567 |             if question:
568 |                 if chat.chat_id is None:
569 |                     chat.create_chat(question)
570 |                 else:
571 |                     chat.query_private_gpt(question)
572 |         except KeyboardInterrupt:
573 |             print("\nExiting chat...")
574 |             break
575 |         except Exception as e:
576 |             print(f"❌ Error: {str(e)}")
577 |             break
578 | 
579 | if __name__ == "__main__":
580 |     main()
```

--------------------------------------------------------------------------------
/clients/Gradio/mcp_servers/filesystem/index.ts:
--------------------------------------------------------------------------------

```typescript
  1 | #!/usr/bin/env node
  2 | 
  3 | import { Server } from "@modelcontextprotocol/sdk/server/index.js";
  4 | import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
  5 | import {
  6 |   CallToolRequestSchema,
  7 |   ListToolsRequestSchema,
  8 |   ToolSchema,
  9 | } from "@modelcontextprotocol/sdk/types.js";
 10 | import fs from "fs/promises";
 11 | import path from "path";
 12 | import os from 'os';
 13 | import { z } from "zod";
 14 | import { zodToJsonSchema } from "zod-to-json-schema";
 15 | import { diffLines, createTwoFilesPatch } from 'diff';
 16 | import { minimatch } from 'minimatch';
 17 | 
 18 | // Command line argument parsing
 19 | const args = process.argv.slice(2);
 20 | if (args.length === 0) {
 21 |   console.error("Usage: mcp-server-filesystem <allowed-directory> [additional-directories...]");
 22 |   process.exit(1);
 23 | }
 24 | 
 25 | // Normalize all paths consistently
 26 | function normalizePath(p: string): string {
 27 |   return path.normalize(p);
 28 | }
 29 | 
 30 | function expandHome(filepath: string): string {
 31 |   if (filepath.startsWith('~/') || filepath === '~') {
 32 |     return path.join(os.homedir(), filepath.slice(1));
 33 |   }
 34 |   return filepath;
 35 | }
 36 | 
 37 | // Store allowed directories in normalized form
 38 | const allowedDirectories = args.map(dir =>
 39 |   normalizePath(path.resolve(expandHome(dir)))
 40 | );
 41 | 
 42 | // Validate that all directories exist and are accessible
 43 | await Promise.all(args.map(async (dir) => {
 44 |   try {
 45 |     const stats = await fs.stat(dir);
 46 |     if (!stats.isDirectory()) {
 47 |       console.error(`Error: ${dir} is not a directory`);
 48 |       process.exit(1);
 49 |     }
 50 |   } catch (error) {
 51 |     console.error(`Error accessing directory ${dir}:`, error);
 52 |     process.exit(1);
 53 |   }
 54 | }));
 55 | 
 56 | // Security utilities
 57 | async function validatePath(requestedPath: string): Promise<string> {
 58 |   const expandedPath = expandHome(requestedPath);
 59 |   const absolute = path.isAbsolute(expandedPath)
 60 |     ? path.resolve(expandedPath)
 61 |     : path.resolve(process.cwd(), expandedPath);
 62 | 
 63 |   const normalizedRequested = normalizePath(absolute);
 64 | 
 65 |   // Check if path is within allowed directories
 66 |   const isAllowed = allowedDirectories.some(dir => normalizedRequested.startsWith(dir));
 67 |   if (!isAllowed) {
 68 |     throw new Error(`Access denied - path outside allowed directories: ${absolute} not in ${allowedDirectories.join(', ')}`);
 69 |   }
 70 | 
 71 |   // Handle symlinks by checking their real path
 72 |   try {
 73 |     const realPath = await fs.realpath(absolute);
 74 |     const normalizedReal = normalizePath(realPath);
 75 |     const isRealPathAllowed = allowedDirectories.some(dir => normalizedReal.startsWith(dir));
 76 |     if (!isRealPathAllowed) {
 77 |       throw new Error("Access denied - symlink target outside allowed directories");
 78 |     }
 79 |     return realPath;
 80 |   } catch (error) {
 81 |     // For new files that don't exist yet, verify parent directory
 82 |     const parentDir = path.dirname(absolute);
 83 |     try {
 84 |       const realParentPath = await fs.realpath(parentDir);
 85 |       const normalizedParent = normalizePath(realParentPath);
 86 |       const isParentAllowed = allowedDirectories.some(dir => normalizedParent.startsWith(dir));
 87 |       if (!isParentAllowed) {
 88 |         throw new Error("Access denied - parent directory outside allowed directories");
 89 |       }
 90 |       return absolute;
 91 |     } catch {
 92 |       throw new Error(`Parent directory does not exist: ${parentDir}`);
 93 |     }
 94 |   }
 95 | }
 96 | 
 97 | // Schema definitions
 98 | const ReadFileArgsSchema = z.object({
 99 |   path: z.string(),
100 | });
101 | 
102 | const ReadMultipleFilesArgsSchema = z.object({
103 |   paths: z.array(z.string()),
104 | });
105 | 
106 | const WriteFileArgsSchema = z.object({
107 |   path: z.string(),
108 |   content: z.string(),
109 | });
110 | 
111 | const EditOperation = z.object({
112 |   oldText: z.string().describe('Text to search for - must match exactly'),
113 |   newText: z.string().describe('Text to replace with')
114 | });
115 | 
116 | const EditFileArgsSchema = z.object({
117 |   path: z.string(),
118 |   edits: z.array(EditOperation),
119 |   dryRun: z.boolean().default(false).describe('Preview changes using git-style diff format')
120 | });
121 | 
122 | const CreateDirectoryArgsSchema = z.object({
123 |   path: z.string(),
124 | });
125 | 
126 | const ListDirectoryArgsSchema = z.object({
127 |   path: z.string(),
128 | });
129 | 
130 | const DirectoryTreeArgsSchema = z.object({
131 |   path: z.string(),
132 | });
133 | 
134 | const MoveFileArgsSchema = z.object({
135 |   source: z.string(),
136 |   destination: z.string(),
137 | });
138 | 
139 | const SearchFilesArgsSchema = z.object({
140 |   path: z.string(),
141 |   pattern: z.string(),
142 |   excludePatterns: z.array(z.string()).optional().default([])
143 | });
144 | 
145 | const GetFileInfoArgsSchema = z.object({
146 |   path: z.string(),
147 | });
148 | 
149 | const ToolInputSchema = ToolSchema.shape.inputSchema;
150 | type ToolInput = z.infer<typeof ToolInputSchema>;
151 | 
152 | interface FileInfo {
153 |   size: number;
154 |   created: Date;
155 |   modified: Date;
156 |   accessed: Date;
157 |   isDirectory: boolean;
158 |   isFile: boolean;
159 |   permissions: string;
160 | }
161 | 
162 | // Server setup
163 | const server = new Server(
164 |   {
165 |     name: "secure-filesystem-server",
166 |     version: "0.2.0",
167 |   },
168 |   {
169 |     capabilities: {
170 |       tools: {},
171 |     },
172 |   },
173 | );
174 | 
175 | // Tool implementations
176 | async function getFileStats(filePath: string): Promise<FileInfo> {
177 |   const stats = await fs.stat(filePath);
178 |   return {
179 |     size: stats.size,
180 |     created: stats.birthtime,
181 |     modified: stats.mtime,
182 |     accessed: stats.atime,
183 |     isDirectory: stats.isDirectory(),
184 |     isFile: stats.isFile(),
185 |     permissions: stats.mode.toString(8).slice(-3),
186 |   };
187 | }
188 | 
189 | async function searchFiles(
190 |   rootPath: string,
191 |   pattern: string,
192 |   excludePatterns: string[] = []
193 | ): Promise<string[]> {
194 |   const results: string[] = [];
195 | 
196 |   async function search(currentPath: string) {
197 |     const entries = await fs.readdir(currentPath, { withFileTypes: true });
198 | 
199 |     for (const entry of entries) {
200 |       const fullPath = path.join(currentPath, entry.name);
201 | 
202 |       try {
203 |         // Validate each path before processing
204 |         await validatePath(fullPath);
205 | 
206 |         // Check if path matches any exclude pattern
207 |         const relativePath = path.relative(rootPath, fullPath);
208 |         const shouldExclude = excludePatterns.some(pattern => {
209 |           const globPattern = pattern.includes('*') ? pattern : `**/${pattern}/**`;
210 |           return minimatch(relativePath, globPattern, { dot: true });
211 |         });
212 | 
213 |         if (shouldExclude) {
214 |           continue;
215 |         }
216 | 
217 |         if (entry.name.toLowerCase().includes(pattern.toLowerCase())) {
218 |           results.push(fullPath);
219 |         }
220 | 
221 |         if (entry.isDirectory()) {
222 |           await search(fullPath);
223 |         }
224 |       } catch (error) {
225 |         // Skip invalid paths during search
226 |         continue;
227 |       }
228 |     }
229 |   }
230 | 
231 |   await search(rootPath);
232 |   return results;
233 | }
234 | 
235 | // file editing and diffing utilities
236 | function normalizeLineEndings(text: string): string {
237 |   return text.replace(/\r\n/g, '\n');
238 | }
239 | 
240 | function createUnifiedDiff(originalContent: string, newContent: string, filepath: string = 'file'): string {
241 |   // Ensure consistent line endings for diff
242 |   const normalizedOriginal = normalizeLineEndings(originalContent);
243 |   const normalizedNew = normalizeLineEndings(newContent);
244 | 
245 |   return createTwoFilesPatch(
246 |     filepath,
247 |     filepath,
248 |     normalizedOriginal,
249 |     normalizedNew,
250 |     'original',
251 |     'modified'
252 |   );
253 | }
254 | 
255 | async function applyFileEdits(
256 |   filePath: string,
257 |   edits: Array<{oldText: string, newText: string}>,
258 |   dryRun = false
259 | ): Promise<string> {
260 |   // Read file content and normalize line endings
261 |   const content = normalizeLineEndings(await fs.readFile(filePath, 'utf-8'));
262 | 
263 |   // Apply edits sequentially
264 |   let modifiedContent = content;
265 |   for (const edit of edits) {
266 |     const normalizedOld = normalizeLineEndings(edit.oldText);
267 |     const normalizedNew = normalizeLineEndings(edit.newText);
268 | 
269 |     // If exact match exists, use it
270 |     if (modifiedContent.includes(normalizedOld)) {
271 |       modifiedContent = modifiedContent.replace(normalizedOld, normalizedNew);
272 |       continue;
273 |     }
274 | 
275 |     // Otherwise, try line-by-line matching with flexibility for whitespace
276 |     const oldLines = normalizedOld.split('\n');
277 |     const contentLines = modifiedContent.split('\n');
278 |     let matchFound = false;
279 | 
280 |     for (let i = 0; i <= contentLines.length - oldLines.length; i++) {
281 |       const potentialMatch = contentLines.slice(i, i + oldLines.length);
282 | 
283 |       // Compare lines with normalized whitespace
284 |       const isMatch = oldLines.every((oldLine, j) => {
285 |         const contentLine = potentialMatch[j];
286 |         return oldLine.trim() === contentLine.trim();
287 |       });
288 | 
289 |       if (isMatch) {
290 |         // Preserve original indentation of first line
291 |         const originalIndent = contentLines[i].match(/^\s*/)?.[0] || '';
292 |         const newLines = normalizedNew.split('\n').map((line, j) => {
293 |           if (j === 0) return originalIndent + line.trimStart();
294 |           // For subsequent lines, try to preserve relative indentation
295 |           const oldIndent = oldLines[j]?.match(/^\s*/)?.[0] || '';
296 |           const newIndent = line.match(/^\s*/)?.[0] || '';
297 |           if (oldIndent && newIndent) {
298 |             const relativeIndent = newIndent.length - oldIndent.length;
299 |             return originalIndent + ' '.repeat(Math.max(0, relativeIndent)) + line.trimStart();
300 |           }
301 |           return line;
302 |         });
303 | 
304 |         contentLines.splice(i, oldLines.length, ...newLines);
305 |         modifiedContent = contentLines.join('\n');
306 |         matchFound = true;
307 |         break;
308 |       }
309 |     }
310 | 
311 |     if (!matchFound) {
312 |       throw new Error(`Could not find exact match for edit:\n${edit.oldText}`);
313 |     }
314 |   }
315 | 
316 |   // Create unified diff
317 |   const diff = createUnifiedDiff(content, modifiedContent, filePath);
318 | 
319 |   // Format diff with appropriate number of backticks
320 |   let numBackticks = 3;
321 |   while (diff.includes('`'.repeat(numBackticks))) {
322 |     numBackticks++;
323 |   }
324 |   const formattedDiff = `${'`'.repeat(numBackticks)}diff\n${diff}${'`'.repeat(numBackticks)}\n\n`;
325 | 
326 |   if (!dryRun) {
327 |     await fs.writeFile(filePath, modifiedContent, 'utf-8');
328 |   }
329 | 
330 |   return formattedDiff;
331 | }
332 | 
333 | // Tool handlers
334 | server.setRequestHandler(ListToolsRequestSchema, async () => {
335 |   return {
336 |     tools: [
337 |       {
338 |         name: "read_file",
339 |         description:
340 |           "Read the complete contents of a file from the file system. " +
341 |           "Handles various text encodings and provides detailed error messages " +
342 |           "if the file cannot be read. Use this tool when you need to examine " +
343 |           "the contents of a single file. Only works within allowed directories.",
344 |         inputSchema: zodToJsonSchema(ReadFileArgsSchema) as ToolInput,
345 |       },
346 |       {
347 |         name: "read_multiple_files",
348 |         description:
349 |           "Read the contents of multiple files simultaneously. This is more " +
350 |           "efficient than reading files one by one when you need to analyze " +
351 |           "or compare multiple files. Each file's content is returned with its " +
352 |           "path as a reference. Failed reads for individual files won't stop " +
353 |           "the entire operation. Only works within allowed directories.",
354 |         inputSchema: zodToJsonSchema(ReadMultipleFilesArgsSchema) as ToolInput,
355 |       },
356 |       {
357 |         name: "write_file",
358 |         description:
359 |           "Create a new file or completely overwrite an existing file with new content. " +
360 |           "Use with caution as it will overwrite existing files without warning. " +
361 |           "Handles text content with proper encoding. Only works within allowed directories.",
362 |         inputSchema: zodToJsonSchema(WriteFileArgsSchema) as ToolInput,
363 |       },
364 |       {
365 |         name: "edit_file",
366 |         description:
367 |           "Make line-based edits to a text file. Each edit replaces exact line sequences " +
368 |           "with new content. Returns a git-style diff showing the changes made. " +
369 |           "Only works within allowed directories.",
370 |         inputSchema: zodToJsonSchema(EditFileArgsSchema) as ToolInput,
371 |       },
372 |       {
373 |         name: "create_directory",
374 |         description:
375 |           "Create a new directory or ensure a directory exists. Can create multiple " +
376 |           "nested directories in one operation. If the directory already exists, " +
377 |           "this operation will succeed silently. Perfect for setting up directory " +
378 |           "structures for projects or ensuring required paths exist. Only works within allowed directories.",
379 |         inputSchema: zodToJsonSchema(CreateDirectoryArgsSchema) as ToolInput,
380 |       },
381 |       {
382 |         name: "list_directory",
383 |         description:
384 |           "Get a detailed listing of all files and directories in a specified path. " +
385 |           "Results clearly distinguish between files and directories with [FILE] and [DIR] " +
386 |           "prefixes. This tool is essential for understanding directory structure and " +
387 |           "finding specific files within a directory. Only works within allowed directories.",
388 |         inputSchema: zodToJsonSchema(ListDirectoryArgsSchema) as ToolInput,
389 |       },
390 |       {
391 |         name: "directory_tree",
392 |         description:
393 |             "Get a recursive tree view of files and directories as a JSON structure. " +
394 |             "Each entry includes 'name', 'type' (file/directory), and 'children' for directories. " +
395 |             "Files have no children array, while directories always have a children array (which may be empty). " +
396 |             "The output is formatted with 2-space indentation for readability. Only works within allowed directories.",
397 |         inputSchema: zodToJsonSchema(DirectoryTreeArgsSchema) as ToolInput,
398 |       },
399 |       {
400 |         name: "move_file",
401 |         description:
402 |           "Move or rename files and directories. Can move files between directories " +
403 |           "and rename them in a single operation. If the destination exists, the " +
404 |           "operation will fail. Works across different directories and can be used " +
405 |           "for simple renaming within the same directory. Both source and destination must be within allowed directories.",
406 |         inputSchema: zodToJsonSchema(MoveFileArgsSchema) as ToolInput,
407 |       },
408 |       {
409 |         name: "search_files",
410 |         description:
411 |           "Recursively search for files and directories matching a pattern. " +
412 |           "Searches through all subdirectories from the starting path. The search " +
413 |           "is case-insensitive and matches partial names. Returns full paths to all " +
414 |           "matching items. Great for finding files when you don't know their exact location. " +
415 |           "Only searches within allowed directories.",
416 |         inputSchema: zodToJsonSchema(SearchFilesArgsSchema) as ToolInput,
417 |       },
418 |       {
419 |         name: "get_file_info",
420 |         description:
421 |           "Retrieve detailed metadata about a file or directory. Returns comprehensive " +
422 |           "information including size, creation time, last modified time, permissions, " +
423 |           "and type. This tool is perfect for understanding file characteristics " +
424 |           "without reading the actual content. Only works within allowed directories.",
425 |         inputSchema: zodToJsonSchema(GetFileInfoArgsSchema) as ToolInput,
426 |       },
427 |       {
428 |         name: "list_allowed_directories",
429 |         description:
430 |           "Returns the list of directories that this server is allowed to access. " +
431 |           "Use this to understand which directories are available before trying to access files.",
432 |         inputSchema: {
433 |           type: "object",
434 |           properties: {},
435 |           required: [],
436 |         },
437 |       },
438 |     ],
439 |   };
440 | });
441 | 
442 | 
443 | server.setRequestHandler(CallToolRequestSchema, async (request) => {
444 |   try {
445 |     const { name, arguments: args } = request.params;
446 | 
447 |     switch (name) {
448 |       case "read_file": {
449 |         const parsed = ReadFileArgsSchema.safeParse(args);
450 |         if (!parsed.success) {
451 |           throw new Error(`Invalid arguments for read_file: ${parsed.error}`);
452 |         }
453 |         const validPath = await validatePath(parsed.data.path);
454 |         const content = await fs.readFile(validPath, "utf-8");
455 |         return {
456 |           content: [{ type: "text", text: content }],
457 |         };
458 |       }
459 | 
460 |       case "read_multiple_files": {
461 |         const parsed = ReadMultipleFilesArgsSchema.safeParse(args);
462 |         if (!parsed.success) {
463 |           throw new Error(`Invalid arguments for read_multiple_files: ${parsed.error}`);
464 |         }
465 |         const results = await Promise.all(
466 |           parsed.data.paths.map(async (filePath: string) => {
467 |             try {
468 |               const validPath = await validatePath(filePath);
469 |               const content = await fs.readFile(validPath, "utf-8");
470 |               return `${filePath}:\n${content}\n`;
471 |             } catch (error) {
472 |               const errorMessage = error instanceof Error ? error.message : String(error);
473 |               return `${filePath}: Error - ${errorMessage}`;
474 |             }
475 |           }),
476 |         );
477 |         return {
478 |           content: [{ type: "text", text: results.join("\n---\n") }],
479 |         };
480 |       }
481 | 
482 |       case "write_file": {
483 |         const parsed = WriteFileArgsSchema.safeParse(args);
484 |         if (!parsed.success) {
485 |           throw new Error(`Invalid arguments for write_file: ${parsed.error}`);
486 |         }
487 |         const validPath = await validatePath(parsed.data.path);
488 |         await fs.writeFile(validPath, parsed.data.content, "utf-8");
489 |         return {
490 |           content: [{ type: "text", text: `Successfully wrote to ${parsed.data.path}` }],
491 |         };
492 |       }
493 | 
494 |       case "edit_file": {
495 |         const parsed = EditFileArgsSchema.safeParse(args);
496 |         if (!parsed.success) {
497 |           throw new Error(`Invalid arguments for edit_file: ${parsed.error}`);
498 |         }
499 |         const validPath = await validatePath(parsed.data.path);
500 |         const result = await applyFileEdits(validPath, parsed.data.edits, parsed.data.dryRun);
501 |         return {
502 |           content: [{ type: "text", text: result }],
503 |         };
504 |       }
505 | 
506 |       case "create_directory": {
507 |         const parsed = CreateDirectoryArgsSchema.safeParse(args);
508 |         if (!parsed.success) {
509 |           throw new Error(`Invalid arguments for create_directory: ${parsed.error}`);
510 |         }
511 |         const validPath = await validatePath(parsed.data.path);
512 |         await fs.mkdir(validPath, { recursive: true });
513 |         return {
514 |           content: [{ type: "text", text: `Successfully created directory ${parsed.data.path}` }],
515 |         };
516 |       }
517 | 
518 |       case "list_directory": {
519 |         const parsed = ListDirectoryArgsSchema.safeParse(args);
520 |         if (!parsed.success) {
521 |           throw new Error(`Invalid arguments for list_directory: ${parsed.error}`);
522 |         }
523 |         const validPath = await validatePath(parsed.data.path);
524 |         const entries = await fs.readdir(validPath, { withFileTypes: true });
525 |         const formatted = entries
526 |           .map((entry) => `${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${entry.name}`)
527 |           .join("\n");
528 |         return {
529 |           content: [{ type: "text", text: formatted }],
530 |         };
531 |       }
532 | 
533 |         case "directory_tree": {
534 |             const parsed = DirectoryTreeArgsSchema.safeParse(args);
535 |             if (!parsed.success) {
536 |                 throw new Error(`Invalid arguments for directory_tree: ${parsed.error}`);
537 |             }
538 | 
539 |             interface TreeEntry {
540 |                 name: string;
541 |                 type: 'file' | 'directory';
542 |                 children?: TreeEntry[];
543 |             }
544 | 
545 |             async function buildTree(currentPath: string): Promise<TreeEntry[]> {
546 |                 const validPath = await validatePath(currentPath);
547 |                 const entries = await fs.readdir(validPath, {withFileTypes: true});
548 |                 const result: TreeEntry[] = [];
549 | 
550 |                 for (const entry of entries) {
551 |                     const entryData: TreeEntry = {
552 |                         name: entry.name,
553 |                         type: entry.isDirectory() ? 'directory' : 'file'
554 |                     };
555 | 
556 |                     if (entry.isDirectory()) {
557 |                         const subPath = path.join(currentPath, entry.name);
558 |                         entryData.children = await buildTree(subPath);
559 |                     }
560 | 
561 |                     result.push(entryData);
562 |                 }
563 | 
564 |                 return result;
565 |             }
566 | 
567 |             const treeData = await buildTree(parsed.data.path);
568 |             return {
569 |                 content: [{
570 |                     type: "text",
571 |                     text: JSON.stringify(treeData, null, 2)
572 |                 }],
573 |             };
574 |         }
575 | 
576 |       case "move_file": {
577 |         const parsed = MoveFileArgsSchema.safeParse(args);
578 |         if (!parsed.success) {
579 |           throw new Error(`Invalid arguments for move_file: ${parsed.error}`);
580 |         }
581 |         const validSourcePath = await validatePath(parsed.data.source);
582 |         const validDestPath = await validatePath(parsed.data.destination);
583 |         await fs.rename(validSourcePath, validDestPath);
584 |         return {
585 |           content: [{ type: "text", text: `Successfully moved ${parsed.data.source} to ${parsed.data.destination}` }],
586 |         };
587 |       }
588 | 
589 |       case "search_files": {
590 |         const parsed = SearchFilesArgsSchema.safeParse(args);
591 |         if (!parsed.success) {
592 |           throw new Error(`Invalid arguments for search_files: ${parsed.error}`);
593 |         }
594 |         const validPath = await validatePath(parsed.data.path);
595 |         const results = await searchFiles(validPath, parsed.data.pattern, parsed.data.excludePatterns);
596 |         return {
597 |           content: [{ type: "text", text: results.length > 0 ? results.join("\n") : "No matches found" }],
598 |         };
599 |       }
600 | 
601 |       case "get_file_info": {
602 |         const parsed = GetFileInfoArgsSchema.safeParse(args);
603 |         if (!parsed.success) {
604 |           throw new Error(`Invalid arguments for get_file_info: ${parsed.error}`);
605 |         }
606 |         const validPath = await validatePath(parsed.data.path);
607 |         const info = await getFileStats(validPath);
608 |         return {
609 |           content: [{ type: "text", text: Object.entries(info)
610 |             .map(([key, value]) => `${key}: ${value}`)
611 |             .join("\n") }],
612 |         };
613 |       }
614 | 
615 |       case "list_allowed_directories": {
616 |         return {
617 |           content: [{
618 |             type: "text",
619 |             text: `Allowed directories:\n${allowedDirectories.join('\n')}`
620 |           }],
621 |         };
622 |       }
623 | 
624 |       default:
625 |         throw new Error(`Unknown tool: ${name}`);
626 |     }
627 |   } catch (error) {
628 |     const errorMessage = error instanceof Error ? error.message : String(error);
629 |     return {
630 |       content: [{ type: "text", text: `Error: ${errorMessage}` }],
631 |       isError: true,
632 |     };
633 |   }
634 | });
635 | 
636 | // Start server
637 | async function runServer() {
638 |   const transport = new StdioServerTransport();
639 |   await server.connect(transport);
640 |   console.error("Secure MCP Filesystem Server running on stdio");
641 |   console.error("Allowed directories:", allowedDirectories);
642 | }
643 | 
644 | runServer().catch((error) => {
645 |   console.error("Fatal error running server:", error);
646 |   process.exit(1);
647 | });
648 | 
```

--------------------------------------------------------------------------------
/ver/index_proxy_np.js:
--------------------------------------------------------------------------------

```javascript
  1 | ![PrivateGPT MCP Server](docs/images/pGPT-MCP.png)
  2 | 
  3 | ## Table of Contents
  4 | - [PrivateGPT MCP Server](#privategpt-mcp-server)
  5 | - [What is MCP?](#what-is-mcp)
  6 |   - [Why MCP?](#why-mcp)
  7 |   - [Why Agents](#why-agents)
  8 |   - [How it Works](#how-it-works) 
  9 | - [Interaction Between Agents, LLMs, and MCP Servers](#interaction-between-agents-llms-and-mcp-servers)
 10 |   - [Scenario](#scenario)
 11 |     1. [User Input](#user-input)
 12 |     2. [Agent Processing](#agent-processing)
 13 |     3. [LLM Interaction](#llm-interaction)
 14 |     4. [Response Processing](#response-processing)
 15 |     5. [Security and Logging](#security-and-logging)
 16 | - [Advantages of Using Agents in This Context](#advantages-of-using-agents-in-this-context)
 17 |   - [Modularity](#modularity)
 18 |   - [Security](#security)
 19 |   - [Efficiency](#efficiency)
 20 |   - [Flexibility](#flexibility)
 21 | - [Overview](#overview)
 22 | - [Security Features Overview](#security)
 23 |   - [1. Password Encryption](#1-password-encryption)
 24 |   - [2. Key Management](#2-key-management)
 25 |   - [3. Decryption on the Server](#3-decryption-on-the-server)
 26 |   - [4. Transport Layer Security (TLS)](#4-transport-layer-security-tls)
 27 |   - [5. Authorization Tokens](#5-authorization-tokens)
 28 |   - [6. Restriction of Key Generation (Keygen)](#6-restriction-of-key-generation-keygen)
 29 |   - [7. Certificate-Based Access Control (CBAC)](#7-certificate-based-access-control-cbac)
 30 |   - [8. Secure Configuration](#8-secure-configuration)
 31 |   - [9. Logging and Monitoring](#9-logging-and-monitoring)
 32 |   - [Summary](#summary)
 33 |   - [Encrypted Password Generation Tool](#encrypted-password-generation-tool)
 34 |     1. [Generate a password for the client and/or the server's Proxy_Config](#generate-encrypted-password)
 35 |     2. [Check the generated encrypted password](#check-the-generated-encrypted-password)
 36 |   - [Encrypted Password Decryption Tool](#encrypted-password-decryption-tool)
 37 |     1. [Check the generated encrypted password](#check-the-generated-encrypted-password)
 38 | - [Feature Overview for PGPT Server](#feature-overview-for-pgpt-server)
 39 |   - [1. **Authentication and Authorization**](#1-authentication-and-authorization)
 40 |   - [2. **Chat Management**](#2-chat-management)
 41 |   - [3. **Group Management**](#3-group-management)
 42 |   - [4. **Source Management**](#4-source-management)
 43 |   - [5. **User Management**](#5-user-management)
 44 |   - [6. **Configuration Flexibility**](#6-configuration-flexibility)
 45 |   - [7. **Error Handling and Logging**](#7-error-handling-and-logging)
 46 |   - [8. **Security Features**](#8-security-features)
 47 |   - [Example Use Cases](#example-use-cases)
 48 |   - [How to Use](#how-to-use)
 49 | - [Installation](#installation)
 50 |   - [Prerequisites](#prerequisites)
 51 |   - [Install Dependencies](#install-dependencies)
 52 |   - [Build the Project](#build-the-project-1)
 53 | - [Configuration Description](#configuration-description)
 54 |   - [Server Configuration](#server-configuration-1)
 55 |   - [PGPT URL](#pgpt-url)
 56 |   - [Server Port](#server-port)
 57 |   - [Language](#language-1)
 58 |   - [SSL Validation](#ssl-validation-1)
 59 |   - [Encryption](#encryption)
 60 |   - [Group Restrictions](#group-restrictions)
 61 |   - [Feature Activation/Deactivation](#feature-activationdeactivation)
 62 | - [Usage](#usage-1)
 63 |   - [Available Tools](#available-tools)
 64 | - [Development](#development-1)
 65 |   - [Building](#building-1)
 66 |   - [Type Checking](#type-checking)
 67 |   - [Linting](#linting)
 68 |   - [Testing](#testing)
 69 | - [Project Structure](#project-structure-1)
 70 | - [Error Handling](#error-handling-1)
 71 | - [License](#license)
 72 | 
 73 | 
 74 | # PrivateGPT MCP Server
 75 | A Model Context Protocol (MCP) server implementation that allows you to use PrivateGPT as an agent for your preferred MCP client. 
 76 | This enables seamless integration between PrivateGPT's powerful capabilities and any MCP-compatible application.
 77 | 
 78 | ## What is MCP?
 79 | MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools.
 80 | 
 81 | ### Why MCP?
 82 | MCP helps you build agents and complex workflows on top of LLMs. LLMs frequently need to integrate with data and tools, and MCP provides:
 83 | - A growing list of pre-built integrations that your LLM can directly plug into
 84 | - The flexibility to switch between LLM providers and vendors
 85 | - Best practices for securing your data within your infrastructure
 86 | 
 87 | ### How it Works
 88 | At its core, MCP follows a client-server architecture where a host application can connect to multiple servers:
 89 | 
 90 | ![MCP General Architecture](docs/images/mcp-general-architecture.png)
 91 | 
 92 | - **MCP Hosts**: Programs like Applications, Claude Desktop, IDEs, or AI tools that want to access data through MCP
 93 | - **MCP Clients**: Protocol clients that maintain 1:1 connections with servers
 94 | - **MCP Servers**: Lightweight programs that each expose specific capabilities through the standardized Model Context Protocol
 95 | - **Local Data Sources**: Your computer's files, databases, and services that MCP servers can securely access
 96 | - **Remote Services**: External systems available over the internet (e.g., through APIs) that MCP servers can connect to
 97 | 
 98 | ## Overview
 99 | This server provides a bridge between MCP clients and the PrivateGPT API, allowing you to:
100 | - Chat with PrivateGPT using both public and private knowledge bases
101 | - Create and manage knowledge sources
102 | - Organize sources into groups
103 | - Control access through group-based permissions
104 | 
105 | 
106 | ---
107 | 
108 | # Why Agents
109 | An **agent** in relation to **LLMs** (Large Language Models) and **MCP servers** is a specialized software component that acts as an intermediary between language models and applications. It handles tasks such as processing requests, interacting with the LLM via MCP, managing workflows, ensuring security and efficiency within the overall system, and much more. By utilizing agents, complex AI-based applications can be designed to be effective, secure, and scalable.
110 | **The code for agents in this repsoitory can be used to implement it into own solutions / applications.**
111 | 
112 | ## Interaction Between Agents, LLMs, and MCP Servers
113 | The interaction of these components enables the development of powerful, scalable, and secure AI applications. Below is a simplified scenario that illustrates this interaction:
114 | 
115 | 1. **User Input:** A user sends a request through a user interface hosted on the MCP server.
116 | 2. **Agent Processing:** An agent on the MCP server receives the request, validates it, and prepares it for the LLM.
117 | 3. **LLM Interaction:** The agent forwards the request to the LLM, which generates a response.
118 | 4. **Response Processing:** The agent receives the response from the LLM, processes it further if necessary (e.g., formatting, integration with other data sources), and sends it back to the user.
119 | 5. **Security and Logging:** During this process, the agent monitors interactions, ensures that security policies are adhered to, and logs relevant information for later analysis.
120 | 
121 | ## Advantages of Using Agents in This Context
122 | - **Modularity:** Agents allow for a clear separation of responsibilities, making the system easier to maintain and scale.
123 | - **Security:** Centralized management of access and monitoring of activities help minimize security risks.
124 | - **Efficiency:** Automated agents can perform tasks faster and more consistently than manual processes.
125 | - **Flexibility:** Agents can be easily adapted or extended to support new functions or changes in business requirements.
126 | 
127 | ### Importance of Encrypting Passwords
128 | In any application handling sensitive data, security is paramount. This server manages two critical sets of credentials:
129 | 1. **Proxy Passwords:** Used by HAProxy to authenticate and manage traffic.
130 | 2. **LLM Access Passwords:** Used to secure access to the large language models.
131 | 
132 | Storing these passwords in plaintext poses significant security risks, including unauthorized access and potential data breaches. 
133 | To mitigate these risks, it is essential to encrypt these passwords and handle only their ciphertext within the system.
134 | 
135 | ### Benefits of Using Ciphertext Only
136 | - **Enhanced Security:** Even if an attacker gains access to the configuration files or environment variables, encrypted passwords remain unintelligible without the corresponding decryption keys.
137 | - **Compliance:** Encryption helps in adhering to security standards and regulations that mandate the protection of sensitive information.
138 | - **Integrity:** Ensures that passwords cannot be tampered with, maintaining the integrity of the authentication mechanisms.
139 | 
140 | ---
141 | 
142 | # Security
143 | The following security features are implemented to ensure data protection and secure communication between the client application and server. These features cover encryption, decryption, key management, and transport security.
144 | 
145 | ## 1. Password Encryption
146 | Passwords can be encrypted using RSA (Rivest–Shamir–Adleman) public-key cryptography. This ensures that sensitive data, such as user passwords, are never transmitted in plaintext.
147 | 
148 | ### Method
149 | - **Public key encryption** with a **2048-bit key length**.
150 | - **Padding**: `RSA_PKCS1_PADDING` to enhance security and prevent known padding attacks.
151 | 
152 | ### Process
153 | 1. The client encrypts the password using the server's public key (`id_rsa_public.pem`).
154 | 2. The encrypted password is sent to the server, where it is decrypted using the server's private key.
155 | 
156 | ### Advantages
157 | - **Asymmetric encryption** ensures that only the server can decrypt the password.
158 | - Even if the communication channel is compromised, encrypted data remains secure.
159 | 
160 | ## 2. Key Management
161 | To secure data communication and encryption processes, the following key management principles are followed:
162 | 
163 | ### Public Key
164 | - Stored securely on the server (`id_rsa_public.pem`).
165 | - Used only for encryption and does not pose a security risk if exposed.
166 | 
167 | ### Private Key
168 | - Stored securely on the server (`id_rsa`).
169 | - Restricted access with appropriate file permissions (`chmod 600`).
170 | - Used exclusively for decryption operations.
171 | 
172 | ### Key Rotation
173 | - Keys are rotated periodically or upon detection of a security incident.
174 | - Old keys are securely invalidated.
175 | 
176 | ## 3. Decryption on the Server
177 | Decryption is exclusively performed on the server using the private key:
178 | 
179 | ### Process
180 | 1. The server receives the encrypted password from the client.
181 | 2. The private key decrypts the password to retrieve the original plaintext.
182 | 3. The decrypted password is used internally (e.g., authentication) and never stored in plaintext.
183 | 
184 | ### Secure Handling
185 | - Decrypted passwords exist in memory only for the duration of processing.
186 | - Secure memory management practices ensure sensitive data is cleared immediately after use.
187 | 
188 | ## 4. Transport Layer Security (TLS)
189 | To secure communication between the client and server:
190 | 
191 | ### TLS Encryption
192 | - All data transmitted between the client and server is encrypted using TLS (minimum version 1.2).
193 | - Prevents man-in-the-middle (MITM) attacks and eavesdropping.
194 | 
195 | ### Certificate Validation
196 | - Certificates are validated on both sides to ensure the authenticity of the server and client.
197 | - Optionally, mutual TLS can be enabled for enhanced security.
198 | 
199 | ## 5. Authorization Tokens
200 | Tokens are used to authenticate requests and ensure only authorized users can access the system:
201 | 
202 | ### Token Management
203 | - Tokens are generated upon successful login.
204 | - They are short-lived and automatically expire after a predefined time.
205 | - Tokens are signed using HMAC or RSA, making them tamper-proof.
206 | 
207 | ### Secure Storage
208 | - Tokens are stored securely on the client side (e.g., in memory or encrypted storage).
209 | 
210 | ## 6. Restriction of Key Generation (Keygen)
211 | To prevent misuse of the system, key generation (`keygen`) is restricted:
212 | 
213 | ### Configuration
214 | - The server has a configuration option (`ALLOW_KEYGEN`) to enable or disable key generation.
215 | - Attempts to call the keygen function when disabled result in an error message.
216 | 
217 | ### Audit Logging
218 | - All keygen operations are logged for auditing and monitoring purposes.
219 | 
220 | ## 7. Certificate-Based Access Control (CBAC)
221 | - As the agent does not require a password when certificate authentication is activated and logs on to the server using a key, it is automatically locked to this server. 
222 | If it would want to log in to another MCP PGPT server, this login attempt is rejected as the key is checked against the server's private certificate. 
223 | 
224 | ### Features
225 | - Functions such as `keygen`, `store_user`, and `edit_source` are only accessible to authorized roles.
226 | - Unauthorized access attempts are denied with detailed error messages.
227 | 
228 | ### Configuration
229 | - Enabled or disabled functions can be specified in the server's configuration (`Functions` object).
230 | 
231 | ## 8. Secure Configuration
232 | The server configuration contains several security-related options:
233 | 
234 | ### SSL_VALIDATE
235 | - Validates SSL/TLS certificates to ensure secure communication.
236 | - Can be enabled or disabled based on environment requirements (e.g., testing vs. production).
237 | 
238 | ### PW_ENCRYPTION
239 | - Enables or disables password encryption.
240 | - Ensures compatibility in environments where encryption is not feasible.
241 | 
242 | ## 9. Logging and Monitoring
243 | All security-related events are logged for monitoring and troubleshooting:
244 | 
245 | ### Logged Events
246 | - Failed login attempts.
247 | - Key generation requests.
248 | - Unauthorized access attempts.
249 | - Encryption and decryption errors.
250 | 
251 | 
252 | ## Summary
253 | The implemented security features ensure:
254 | 
255 | - **Confidentiality** of sensitive data through encryption and secure transport.
256 | - **Integrity** of operations using robust key management and token validation.
257 | - **Role-based and configurable access control** for system functions.
258 | - **Comprehensive monitoring** for proactive detection and response to security threats.
259 | 
260 | These measures collectively provide a secure environment for client-server communication and data handling.
261 | 
262 | 
263 | # Feature Overview for PGPT Server
264 | The PGPT Server offers a robust set of features designed to provide efficient, flexible, and secure communication with the Model Context Protocol (MCP). Below is an overview of the key features and functionalities available in the server.
265 | 
266 | ---
267 | 
268 | ## Key Features
269 | 
270 | ### 1. **Authentication and Authorization**
271 | - **Login Functionality**: Authenticate users with email and password to generate access tokens.
272 | - **Logout Functionality**: Securely invalidate user tokens to end sessions.
273 | 
274 | ---
275 | 
276 | ### 2. **Chat Management**
277 | - **Start a Chat**: Initiate a conversation with the server, optionally using public knowledge bases or specific group contexts.
278 | - **Continue a Chat**: Resume an ongoing conversation by providing the chat ID and a follow-up message.
279 | - **Retrieve Chat Information**: Fetch metadata and messages for a specific chat by its ID.
280 | 
281 | ---
282 | 
283 | ### 3. **Group Management**
284 | - **List Groups**: View personal and assignable groups available to the user.
285 | - **Create Groups**: Add new groups with names and descriptions for organizational purposes.
286 | - **Delete Groups**: Remove existing groups (if enabled in configuration).
287 | 
288 | ---
289 | 
290 | ### 4. **Source Management**
291 | - **Create Sources**: Add new sources with content and assign them to specific groups.
292 | - **Edit Sources**: Update existing sources with new content or metadata.
293 | - **Delete Sources**: Remove sources that are no longer needed.
294 | - **Retrieve Sources**: Fetch information about a specific source by its ID.
295 | - **List Sources**: View all sources assigned to a specific group.
296 | 
297 | ---
298 | 
299 | ### 5. **User Management**
300 | - **Create Users**: Register new users with customizable roles, groups, and settings.
301 | - **Edit Users**: Update user information, including name, email, password, and roles.
302 | - **Delete Users**: Remove users from the system (if enabled in configuration).
303 | 
304 | ---
305 | 
306 | ### 6. **Configuration Flexibility**
307 | - **Function Activation/Deactivation**: Enable or disable individual server functionalities through the `.env` configuration file.
308 | - **Language Support**: Customize the server's system messages to your preferred language (e.g., English or German).
309 | - **SSL Validation**: Toggle SSL validation for secure connections to the server.
310 | 
311 | ---
312 | 
313 | ### 7. **Error Handling and Logging**
314 | - Detailed error messages and logging for:
315 |   - Invalid requests
316 |   - Authentication failures
317 |   - API communication issues
318 | - Configurable responses when a disabled function is accessed.
319 | 
320 | ---
321 | 
322 | ### 8. **Security Features**
323 | - **Token-Based Authentication**: Ensures secure and controlled access to server features.
324 | - **Restricted Group Access**: Option to limit access to `assignableGroups` for enhanced privacy.
325 | 
326 | ---
327 | 
328 | ### Example Use Cases
329 | 1. **Customer Support**: Use chat features to build intelligent conversational agents.
330 | 2. **Knowledge Management**: Manage and retrieve structured data with sources and groups.
331 | 3. **Multi-User Collaboration**: Create, edit, and assign users to groups for collaborative workflows.
332 | 4. **Customizable Functionality**: Activate only the features you need for your application.
333 | 
334 | ---
335 | 
336 | ### How to Use
337 | 1. Configure the server by editing the `.env` file.
338 | 2. Start the server using the provided script.
339 | 3. Interact with the server via API calls to utilize its features.
340 | 
341 | Refer to the **API Documentation** for detailed usage instructions and examples for each endpoint.
342 | 
343 | ---
344 | 
345 | The PGPT Server is a powerful tool for managing structured communication and data in a customizable environment. Tailor its features to your needs for maximum efficiency and control.
346 | 
347 | 
348 | ## Installation
349 | 1. Clone the repository:
350 | ```bash
351 | git clone https://github.com/pgpt-dev/MCP-Server-for-MAS-Developments.git
352 | cd MCP-Server-for-MAS-Developments
353 | ```
354 | 
355 | 2. Install npm:
356 | ```bash
357 | sudo apt install npm
358 | ```
359 | 3. Install Dependencies
360 | ```bash
361 | npm install
362 | ```
363 | 
364 |    and 
365 | 
366 | ```bash
367 | npm install dotenv
368 | npm install moment
369 | ```
370 | 
371 | 4. Build the project:
372 | ```bash
373 | npm run build
374 | ```
375 | 
376 | ---
377 | 
378 | ## Configuration Description
379 | 
380 | ### Server Configuration
381 | 
382 | For secure certificate authentification, create a `.env` file with your PrivateGPT credentials, for example pgpt.env.json 
383 | Settings can be adjusted in the `.env` file to customize the server and its functionalities.
384 | 
385 | Generate the cerificates, .pem files are needed:
386 | ```bash
387 | ssh-keygen -f ~/.ssh/id_rsa.pub -e -m PEM > ~/.ssh/id_rsa_public.pem
388 | ssh-keygen -p -m PEM -f ~/.ssh/id_rsa
389 | ```
390 | 
391 | After this process, you can create Ciphertext from passwords by using the Encrypted Password Encryption Tool and test the cipher with the Encrypted Password Decryption Tool.
392 | You will find the descriptionof how it works in the `Security` section of this document.
393 | 
394 | ---
395 | 
396 | Below is a sample `.env` configuration file for the PGPT server, including descriptions for each setting. 
397 | Customize these values to fit your environment and requirements.
398 | 
399 | ---
400 | 
401 | ## PGPT URL
402 | 
403 | | Key                       | Description                                              | Example Value                                |
404 | |---------------------------|----------------------------------------------------------|----------------------------------------------|
405 | | **PRIVATE_GPT_API_URL**   | The base URL of the Private GPT API.                     | `https://<YOUR DOMAIN OR IP>/api/v1`         |
406 | | **API_URL**               | Alias for the base API URL.                              | `https://*<YOUR DOMAIN OR IP>*/api/v1`       |
407 | 
408 | ---
409 | 
410 | ## Server Port
411 | | Key      | Description                                    | Example Value |
412 | |----------|------------------------------------------------|---------------|
413 | | **PORT** | The port on which the MCP server runs.         | `5000`        |
414 | 
415 | ---
416 | 
417 | ## Language
418 | | Key        | Description                                                         | Example Value |
419 | |------------|---------------------------------------------------------------------|---------------|
420 | | **LANGUAGE** | The language for the server's system messages (`en` or `de`).     | `"de"`        |
421 | 
422 | ---
423 | 
424 | ## SSL Validation
425 | | Key            | Description                                                                             | Example Value |
426 | |----------------|-----------------------------------------------------------------------------------------|---------------|
427 | | **SSL_VALIDATE** | Use `"false"` only if the server's certificate cannot be validated by the client.     | `"false"`     |
428 | 
429 | ---
430 | 
431 | ## Encryption
432 | | Key               | Description                                                                          | Example Value                    |
433 | |-------------------|--------------------------------------------------------------------------------------|----------------------------------|
434 | | **PW_ENCRYPTION** | If set to `"true"` the server only accepts passwords in Ciphertext.                  | `"false"`                        |
435 | | **PUBLIC_KEY**    | Specifies the file system path to the server's public PEM file used for SSL/TLS.     | `"~/.ssh/id_rsa_public.pem"`     |
436 | | **PRIVATE_KEY**   | Specifies the file system path to the server's private key file used for decryption. | `"~/.ssh/id_rsa_public.pem"`     |
437 | 
438 | ---
439 | 
440 | ## Group Restrictions
441 | | Key                 | Description                                                                                     | Example Value |
442 | |---------------------|-------------------------------------------------------------------------------------------------|---------------|
443 | | **RESTRICTED_GROUPS** | Setting `true` prevents client access to `assignableGroups`.                                  | `false`       |
444 | 
445 | ---
446 | 
447 | ## Feature Activation/Deactivation
448 | Control the availability of individual server functions. Set the corresponding value to `true` to enable the function, or `false` to disable it. Disabled functions will return a message indicating they are not available.
449 | 
450 | | Key                       | Description                                        | Example Value |
451 | |---------------------------|----------------------------------------------------|---------------|
452 | | **ENABLE_LOGIN**          | Enables or disables the login function.            | `true`        |
453 | | **ENABLE_LOGOUT**         | Enables or disables the logout function.           | `true`        |
454 | | **ENABLE_CHAT**           | Enables or disables the chat functionality.        | `true`        |
455 | | **ENABLE_CONTINUE_CHAT**  | Enables or disables continuing a chat.             | `true`        |
456 | | **ENABLE_GET_CHAT_INFO**  | Enables or disables retrieving chat information.   | `true`        |
457 | | **ENABLE_LIST_GROUPS**    | Enables or disables listing groups.                | `true`        |
458 | | **ENABLE_STORE_GROUP**    | Enables or disables creating a group.              | `true`        |
459 | | **ENABLE_DELETE_GROUP**   | Enables or disables deleting a group.              | `false`       |
460 | | **ENABLE_CREATE_SOURCE**  | Enables or disables creating a source.             | `true`        |
461 | | **ENABLE_EDIT_SOURCE**    | Enables or disables editing a source.              | `true`        |
462 | | **ENABLE_DELETE_SOURCE**  | Enables or disables deleting a source.             | `true`        |
463 | | **ENABLE_GET_SOURCE**     | Enables or disables retrieving a source.           | `true`        |
464 | | **ENABLE_LIST_SOURCES**   | Enables or disables listing sources.               | `true`        |
465 | | **ENABLE_STORE_USER**     | Enables or disables creating a user.               | `true`        |
466 | | **ENABLE_EDIT_USER**      | Enables or disables editing a user.                | `false`       |
467 | | **ENABLE_DELETE_USER**    | Enables or disables deleting a user.               | `false`       |
468 | 
469 | ---
470 | 
471 | ## Usage
472 | - **Enable a Function**: Set the corresponding value in the `.env` file to `true`.
473 | - **Disable a Function**: Set the corresponding value in the `.env` file to `false`.
474 |   - The server will respond with a message indicating that the function is disabled.
475 | 
476 | Example `.env` entry:
477 | ```dotenv
478 | {
479 |     "PGPT_Url": {
480 |         "PRIVATE_GPT_API_URL": "https://<YOUR_PGPT_URL>/api/v1",
481 |         "API_URL": "https://<YOUR_PGPT_URL>/api/v1"
482 |     },
483 |     "Proxy_Config": {
484 |     "USE_PROXY": "true",
485 |     "AUTH_REQUIRED": "true",
486 |     "UNSECURE_PW": "false",
487 |     "USER": "username@<MY_PGPT_DOMAIN>",
488 |     "PASSWORD": "Example: H3i2ufJEV8v5eQTeArvKIvl..."
489 |     },        
490 |     "Server_Config": {
491 |         "PORT": 5000,
492 |         "LANGUAGE": "en",
493 |         "SSL_VALIDATE": "false",
494 |         "PW_ENCRYPTION": "true",
495 |         "ALLOW_KEYGEN": "false",
496 |         "PUBLIC_KEY": "/<SERVER_PATH>/.ssh/id_rsa_public.pem",
497 |         "PRIVATE_KEY": "/<SERVER_PATH>/.ssh/id_rsa"
498 |     },
499 |     "Restrictions": {
500 |         "RESTRICTED_GROUPS": false
501 |     },
502 |     "Functions": {
503 |         "ENABLE_LOGIN": true,
504 |         "ENABLE_LOGOUT": true,
505 |         "ENABLE_CHAT": true,
506 |         "ENABLE_CONTINUE_CHAT": true,
507 |         "ENABLE_GET_CHAT_INFO": true,
508 |         "ENABLE_LIST_GROUPS": true,
509 |         "ENABLE_STORE_GROUP": true,
510 |         "ENABLE_DELETE_GROUP": false,
511 |         "ENABLE_CREATE_SOURCE": true,
512 |         "ENABLE_EDIT_SOURCE": true,
513 |         "ENABLE_DELETE_SOURCE": false,
514 |         "ENABLE_GET_SOURCE": true,
515 |         "ENABLE_LIST_SOURCES": true,
516 |         "ENABLE_STORE_USER": true,
517 |         "ENABLE_EDIT_USER": false,
518 |         "ENABLE_DELETE_USER": false
519 |     }
520 | }
521 | ```
522 | 
523 | ## Usage
524 | Start the server:
525 | ```bash
526 | node dist/index.js
527 | ```
528 | 
529 | The server will start and listen on stdio for MCP commands.
530 | 
531 | ## Project Structure
532 | ```
533 | src/
534 |   ├── index.js                        # Main server implementation
535 |   ├── types/                          # TypeScript type definitions
536 |   │   └── api.ts                      # API interface types
537 |   └── security/                       # Security Tools
538 |   │   └── generate_encrypted_password # Encrypt the passwod and use Cyphertext for login. It replaces the plain text password in the --password parameter and has to executed on the server.
539 |   │   └── generate_decrypted_password # Decrypt the Cyphertext to get the password. Execute it on the server to ensure the cyphertext contains the correct password.
540 |   └── services/                       # Service implementations
541 |   │   └── pgpt-service.ts             # PrivateGPT API service
542 |   └── clients/                        # Service implementations
543 |       └── Python                      # **Python**
544 |       │	  └── mcp...                  # Client examples written in Python
545 |       └── C# .Net                     # **C#**
546 |       │	  └── Code                    # Original files
547 |       │	    └── mcp...                # Client examples written in C#
548 |       └── C++                         # **C++**
549 |       │	  └── mcp...                  # Client examples written in C++
550 |       └── Java                        # **Java**
551 |       │	  └── mcp...                  # Client examples written in Java
552 |       └── JavaScrip                   # **JavaScript**
553 |       │	  └── mcp...                  # Client examples written in JavaScript
554 |       └── PHP                         # **PHP**
555 |       │	  └── mcp...                  # Client examples written in PHP
556 |       └── Go                          # **Go**
557 |           └── mcp...                  # Client examples written in Go
558 | ```
559 | 
560 | ## Error Handling
561 | The server handles various error scenarios:
562 | - Authentication failures
563 | - Network errors
564 | - Invalid requests
565 | - API errors
566 | - Rate limiting
567 | - Timeout errors
568 | 
569 | Errors are mapped to appropriate MCP error codes and include detailed messages for debugging.
570 | 
571 | ## Available Tools
572 | 
573 | ### Generate Encrypted Password
574 | Generate a password for the client and/or the server's Proxy_Config->Password entry:
575 | ```bash
576 |  node security/generate_encrypted_password.js ~/.ssh/id_rsa_public.pem
577 | ```
578 | 
579 | ### Check the generated encrypted password
580 | To check the encrytion use:
581 | ```bash
582 |  node security/generate_decrypted_password.js ~/.ssh/id_rsa
583 | ```
584 | 
585 | See the sections `Encrypted Password Generation Tool` and `Encrypted Password Decryption Tool` below for further information
586 | 
587 | ---
588 | 
589 | # Encrypted Password Generation Tool
590 | 
591 | ## Overview
592 | The **Encrypted Password Generation Tool** is a Node.js script designed to securely encrypt user passwords using RSA public-key cryptography. This tool ensures that sensitive password data remains protected during transmission and storage by leveraging robust encryption mechanisms. It is an essential component for systems requiring secure password handling and transmission between clients and servers.
593 | 
594 | ## Features
595 | - **Secure Encryption:** Utilizes RSA (Rivest–Shamir–Adleman) public-key cryptography to encrypt sensitive passwords.
596 | - **User-Friendly Interface:** Prompts users to input their passwords securely via the command line.
597 | - **Error Handling:** Provides comprehensive error messages for missing keys or encryption issues.
598 | - **Flexible Integration:** Can be integrated into larger systems requiring secure password handling and encryption.
599 | 
600 | ## How It Works
601 | 1. **Public Key Loading:** The script loads the RSA public key from a specified file path provided as a command-line argument.
602 | 2. **Password Input:** It prompts the user to enter their password securely via the command line.
603 | 3. **Encryption Process:** Using the loaded public key and `RSA_PKCS1_PADDING`, the script encrypts the entered password.
604 | 4. **Output:** The encrypted password is displayed in Base64 format, ready for secure transmission or storage.
605 | 
606 | ## Prerequisites
607 | - **Node.js:** Ensure that Node.js is installed on your system. You can download it from the [Node.js Official Website](https://nodejs.org/).
608 | - **RSA Public Key:** You must have access to the RSA public key (`id_rsa_public.pem`) used for encrypting the password.
609 | 
610 | ## Installation
611 | -  **Install Dependencies:**
612 |     The script uses built-in Node.js modules, so no additional dependencies are required. However, ensure that your Node.js version supports ES6 modules.
613 |     ```bash
614 |     npm install
615 |     ```
616 | 
617 | ## Usage
618 | 1. **Prepare Your RSA Public Key:**
619 |     Ensure you have your RSA public key (`id_rsa_public.pem`) stored securely on your MCP server.
620 | 
621 | 2. **Run the Script, you will find it at the `security` directory of the MCP server:**
622 |     Execute the script using Node.js, providing the path to your public key as a command-line argument.
623 |     ```bash
624 |     node encrypt_password.js /path/to/your/id_rsa_public.pem
625 |     ```
626 | 
627 |     **Example:**
628 |     ```bash
629 |     node security/encrypt_password.js ~/.ssh/id_rsa_public.pem
630 |     ```
631 | 
632 | 3. **Enter Your Password:**
633 |     When prompted, input your password securely.
634 |     ```bash
635 |     Please enter your password: ********
636 |     ```
637 | 
638 | 4. **View the Encrypted Password:**
639 |     The script will output the encrypted password in Base64 format.
640 |     ```bash
641 |     Encrypted Password: <Your_Encrypted_Password>
642 |     ```
643 | 
644 | ---
645 | 
646 | # Encrypted Password Decryption Tool
647 | 
648 | ## Overview
649 | The **Encrypted Password Decryption Tool** is a Node.js script designed to securely decrypt encrypted passwords using RSA private-key cryptography. 
650 | This tool ensures that sensitive password data remains protected during transmission and storage by leveraging robust encryption and decryption mechanisms.
651 | To verify or decrypt an encrypted password, use the private key. This is helpful to ensure that the encryption was performed correctly.
652 | 
653 | ## Features
654 | - **Secure Decryption:** Utilizes RSA (Rivest–Shamir–Adleman) private-key cryptography to decrypt sensitive password data.
655 | - **Error Handling:** Provides comprehensive error messages for missing keys or decryption issues.
656 | - **User-Friendly Interface:** Prompts users to input encrypted passwords securely via the command line.
657 | - **Flexible Integration:** Can be integrated into larger systems requiring secure password handling.
658 | 
659 | ## How It Works
660 | 1. **Private Key Loading:** The script loads the RSA private key from a specified file path provided as a command-line argument.
661 | 2. **Encrypted Password Input:** It prompts the user to enter an encrypted password in Base64 format.
662 | 3. **Decryption Process:** Using the loaded private key and RSA_PKCS1_PADDING, the script decrypts the encrypted password.
663 | 4. **Output:** The decrypted plaintext password is displayed in the console.
664 | 
665 | ## Prerequisites
666 | - **Node.js:** Ensure that Node.js is installed on your system. You can download it from [Node.js Official Website](https://nodejs.org/).
667 | - **RSA Private Key:** You must have access to the RSA private key (`id_rsa`) on your MCP server used for decrypting the password.
668 | 
669 | ## Installation
670 | - **Install Dependencies:**
671 |     The script uses built-in Node.js modules, so no additional dependencies are required. However, ensure that your Node.js version supports ES6 modules.
672 | 
673 | ## Usage
674 | 1. **Prepare Your RSA Private Key:**
675 |     Ensure you have your RSA private key (`id_rsa`) stored securely on your machine.
676 | 
677 | 2. **Run the Script, you will find it at the `security` directory of the MCP server:**:**
678 |     Execute the script using Node.js, providing the path to your private key as a command-line argument.
679 |     ```bash
680 |     node decrypt_password.js /path/to/your/id_rsa
681 |     ```
682 | 
683 |     **Example:**
684 |     ```bash
685 |     node decrypt_password.js ~/.ssh/id_rsa
686 |     ```
687 | 
688 | 3. **Enter the Encrypted Password:**
689 |     When prompted, input the encrypted password in Base64 format.
690 |     ```bash
691 |     Please enter the encrypted password: <Your_Encrypted_Password>
692 |     ```
693 | 
694 | 4. **View the Decrypted Password:**
695 |     The script will output the decrypted plaintext password.
696 |     ```bash
697 |     Decrypted Password: your_plaintext_password
698 |     ```
699 | This will decrypt the encrypted password and display the original value.
700 | 
701 | 
702 | ### Notes
703 | - Ensure that the `~/.ssh/id_rsa_public.pem` (public key) and `~/.ssh/id_rsa` (private key) files exist and have the correct permissions.
704 | - The encryption tool relies on the public key, while the decryption tool requires the private key.
705 | 
706 | ## License
707 | This project is licensed under the MIT License - see the LICENSE file for details.
708 | 
```
Page 16/20FirstPrevNextLast