Metadata-Version: 2.4
Name: sqlserver-mcp-server
Version: 1.0.0
Summary: A comprehensive Model Context Protocol (MCP) server for interacting with SQL Server databases
Project-URL: Homepage, https://github.com/your-org/sqlserver-mcp-server
Project-URL: Documentation, https://github.com/your-org/sqlserver-mcp-server#readme
Project-URL: Repository, https://github.com/your-org/sqlserver-mcp-server.git
Project-URL: Issues, https://github.com/your-org/sqlserver-mcp-server/issues
Project-URL: Changelog, https://github.com/your-org/sqlserver-mcp-server/blob/main/CHANGELOG.md
Project-URL: Download, https://pypi.org/project/sqlserver-mcp-server/#files
Author-email: SQL Server MCP Server Team <sqlserver-mcp@example.com>
Maintainer-email: SQL Server MCP Server Team <sqlserver-mcp@example.com>
License: GNU LESSER GENERAL PUBLIC LICENSE
        Version 3, 29 June 2007
        
        Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
        Everyone is permitted to copy and distribute verbatim copies
        of this license document, but changing it is not allowed.
        
        
        This version of the GNU Lesser General Public License incorporates
        the terms and conditions of version 3 of the GNU General Public
        License, supplemented by the additional permissions listed below.
        
        0. Additional Definitions.
        
        As used herein, "this License" refers to version 3 of the GNU Lesser
        General Public License, and the "GNU GPL" refers to version 3 of the GNU
        General Public License.
        
        "The Library" refers to a covered work governed by this License,
        other than an Application or a Combined Work as defined below.
        
        An "Application" is any work that makes use of an interface provided
        by the Library, but which is not otherwise based on the Library.
        Defining a subclass of a class defined by the Library is deemed a mode
        of using an interface provided by the Library.
        
        A "Combined Work" is a work produced by combining or linking an
        Application with the Library.  The particular version of the Library
        with which the Combined Work was made is also called the "Linked
        Version".
        
        The "Minimal Corresponding Source" for a Combined Work means the
        Corresponding Source for the Combined Work, excluding any source code
        for portions of the Combined Work that, considered in isolation, are
        based on the Application, and not on the Linked Version.
        
        The "Corresponding Application Code" for a Combined Work means the
        object code and/or source code for the Application, including any data
        and utility programs needed for reproducing the Combined Work from the
        Application (but excluding the System Libraries of the Combined Work).
        
        1. Exception to Section 3 of the GNU GPL.
        
        You may convey a covered work under sections 3 and 4 of this License
        without being bound by section 3 of the GNU GPL.
        
        2. Conveying Modified Versions.
        
        If you modify a copy of the Library, and, in your modifications, a
        facility refers to a function or data to be supplied by an Application
        that uses the facility (other than as an argument passed when the
        facility is invoked), then you may convey a copy of the modified version:
        
        a) under this License, provided that you make a good faith effort to
           ensure that, in the event an Application does not supply the
           function or data, the facility still operates, and performs
           whatever part of its purpose remains meaningful, or
        
        b) under the GNU GPL, with none of the additional permissions of
           this License applicable to that copy.
        
        3. Object Code Incorporating Material from Library Header Files.
        
        The object code form of an Application may incorporate material from
        a header file that is part of the Library.  You may convey such object
        code under terms of your choice, provided that, if the incorporated
        material is not limited to numerical parameters, data structure
        layouts and accessors, or small macros, inline functions and templates
        (ten or fewer lines in length), you do both of the following:
        
        a) Give prominent notice with each copy of the object code that the
           Library is used in it and that the Library and its use are
           covered by this License.
        
        b) Accompany the object code with a copy of the GNU GPL and this license
           document.
        
        4. Combined Works.
        
        You may convey a Combined Work under terms of your choice that,
        taken together, effectively do not restrict modification of the
        portions of the Library contained in the Combined Work and reverse
        engineering for debugging such modifications, if you also do each of
        the following:
        
        a) Give prominent notice with each copy of the Combined Work that
           the Library is used in it and that the Library and its use are
           covered by this License.
        
        b) Accompany the Combined Work with a copy of the GNU GPL and this license
           document.
        
        c) For a Combined Work that displays copyright notices during
           execution, include the copyright notice for the Library among
           these notices, as well as a reference directing the user to the
           copies of the GNU GPL and this license document.
        
        d) Do one of the following:
        
            0) Convey the Minimal Corresponding Source under the terms of this
               License, and the Corresponding Application Code in a form
               suitable for, and under terms that permit, the user to
               recombine or relink the Application with a modified version of
               the Linked Version to produce a modified Combined Work, in the
               manner specified by section 6 of the GNU GPL for conveying
               Corresponding Source.
        
            1) Use a suitable shared library mechanism for linking with the
               Library.  A suitable mechanism is one that (a) uses at run time
               a copy of the Library already present on the user's computer
               system, and (b) will operate properly with a modified version
               of the Library that is interface-compatible with the Linked
               Version.
        
        e) Provide Installation Information, but only if you would otherwise
           be required to provide such information under section 6 of the
           GNU GPL, and only to the extent that such information is
           necessary to install and execute a modified version of the
           Combined Work produced by recombining or relinking the
           Application with a modified version of the Linked Version. (If
           you use option 4d0, the Installation Information must accompany
           the Minimal Corresponding Source and Corresponding Application
           Code. If you use option 4d1, you must provide the Installation
           Information in the manner specified by section 6 of the GNU GPL
           for conveying Corresponding Source.)
        
        5. Combined Libraries.
        
        You may place library facilities that are a work based on the
        Library side by side in a single library together with other library
        facilities that are not Applications and are not covered by this
        License, and convey such a combined library under terms of your
        choice, if you do both of the following:
        
        a) Accompany the combined library with a copy of the same work based
           on the Library, uncombined with any other library facilities,
           conveyed under the terms of this License.
        
        b) Give prominent notice with the combined library that part of it
           is a work based on the Library, and explaining where to find the
           accompanying uncombined form of the same work.
        
        6. Revised Versions of the GNU Lesser General Public License.
        
        The Free Software Foundation may publish revised and/or new versions
        of the GNU Lesser General Public License from time to time. Such new
        versions will be similar in spirit to the present version, but may
        differ in detail to address new problems or concerns.
        
        Each version is given a distinguishing version number. If the
        Library as you received it specifies that a certain numbered version
        of the GNU Lesser General Public License "or any later version"
        applies to it, you have the option of following the terms and
        conditions either of that published version or of any later version
        published by the Free Software Foundation. If the Library as you
        received it does not specify a version number of the GNU Lesser
        General Public License, you may choose any version of the GNU Lesser
        General Public License ever published by the Free Software Foundation.
        
        If the Library as you received it specifies that a proxy can decide
        whether future versions of the GNU Lesser General Public License shall
        apply, that proxy's public statement of acceptance of any version is
        permanent authorization for you to choose that version for the
        Library.
        
        ---
        
        Copyright (c) 2024 SQL Server MCP Server
        
        This library is free software; you can redistribute it and/or
        modify it under the terms of the GNU Lesser General Public
        License as published by the Free Software Foundation; either
        version 3 of the License, or (at your option) any later version.
        
        This library is distributed in the hope that it will be useful,
        but WITHOUT ANY WARRANTY; without even the implied warranty of
        MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
        Lesser General Public License for more details.
        
        You should have received a copy of the GNU Lesser General Public
        License along with this library; if not, write to the Free Software
        Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
License-File: LICENSE
Keywords: ai,assistant,database,mcp,model-context-protocol,odbc,protocol,pyodbc,sql-server,sqlserver
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Environment :: Web Environment
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Database
Classifier: Topic :: Database :: Database Engines/Servers
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Networking
Requires-Python: >=3.8
Requires-Dist: click>=8.0.0
Requires-Dist: mcp>=1.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pyodbc>=4.0.39
Requires-Dist: rich>=13.0.0
Requires-Dist: structlog>=23.0.0
Provides-Extra: dev
Requires-Dist: bandit>=1.7.0; extra == 'dev'
Requires-Dist: black>=23.0.0; extra == 'dev'
Requires-Dist: flake8>=6.0.0; extra == 'dev'
Requires-Dist: isort>=5.12.0; extra == 'dev'
Requires-Dist: mypy>=1.0.0; extra == 'dev'
Requires-Dist: pre-commit>=3.3.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-benchmark>=4.0.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: safety>=2.0.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.0.0; extra == 'docs'
Requires-Dist: mkdocs>=1.4.0; extra == 'docs'
Requires-Dist: mkdocstrings>=0.20.0; extra == 'docs'
Provides-Extra: test
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'test'
Requires-Dist: pytest-benchmark>=4.0.0; extra == 'test'
Requires-Dist: pytest-cov>=4.0.0; extra == 'test'
Requires-Dist: pytest-mock>=3.10.0; extra == 'test'
Requires-Dist: pytest>=7.0.0; extra == 'test'
Description-Content-Type: text/markdown

# SQL Server MCP Server

[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0)
[![MCP Protocol](https://img.shields.io/badge/MCP-Protocol-green.svg)](https://modelcontextprotocol.io/)

A comprehensive Model Context Protocol (MCP) server for interacting with SQL Server databases. This server provides AI assistants with secure, efficient access to SQL Server databases through standardized MCP tools and resources.

## ✨ Features

- **🔗 Database Connection Management**: Secure connection pooling with Windows and SQL Server authentication
- **📊 Query Execution**: Execute SQL queries with parameterized queries and multiple output formats
- **🔍 Schema Inspection**: Retrieve detailed database schema information including tables, columns, indexes, and relationships
- **📋 Data Retrieval**: Get table data with pagination, filtering, and sorting capabilities
- **🖥️ CLI Interface**: Full command-line interface for all MCP capabilities
- **🛡️ Security**: SQL injection prevention, secure authentication, and credential management
- **⚡ Performance**: Connection pooling, query optimization, and performance monitoring
- **📚 Full MCP Protocol Compliance**: Complete implementation of MCP protocol standards

## 🚀 Installation

### Prerequisites

- Python 3.8 or higher
- SQL Server instance (local or remote)
- ODBC Driver 17 for SQL Server

### Install from Source

```bash
git clone https://github.com/your-org/sqlserver-mcp-server.git
cd sqlserver-mcp-server
pip install -e .
```

### Install Dependencies

```bash
pip install -r requirements.txt
```

## 🏃‍♂️ Quick Start

### Start MCP Server

```bash
# Start the MCP server
python -m src.mcp_tools

# Or use the CLI entry point
sqlserver-mcp server
```

### Use CLI Interface

```bash
# Connect to database
sqlserver-mcp connect --server "localhost" --database "master" --trusted-connection

# Execute query
sqlserver-mcp query --connection-id <connection-id> "SELECT * FROM sys.tables"

# List databases
sqlserver-mcp list-databases --connection-id <connection-id>

# Get table schema
sqlserver-mcp get-schema --connection-id <connection-id> --table "users"
```

## 🛠️ MCP Tools

The server provides the following MCP tools:

| Tool | Description | Parameters |
|------|-------------|------------|
| `create_connection` | Establish database connections | server, database, authentication |
| `execute_query` | Execute SQL queries | query, database, timeout, parameters |
| `get_schema` | Retrieve schema information | database, table_name, include_relationships |
| `get_table_data` | Get table data with pagination | table_name, limit, offset, where_clause |
| `list_databases` | List available databases | include_system, include_metadata |

## 📖 MCP Resources

The server provides the following MCP resources:

| Resource | Description | URI |
|----------|-------------|-----|
| `connection_status` | Real-time connection health and metrics | `mcp://sqlserver/connection_status` |
| `query_history` | Query execution history and statistics | `mcp://sqlserver/query_history` |

## ⚙️ Configuration

### Environment Variables

```bash
export SQLSERVER_MCP_LOG_LEVEL=INFO
export SQLSERVER_MCP_SERVER_HOST=127.0.0.1
export SQLSERVER_MCP_SERVER_PORT=8000
```

### Configuration File

Create a `config.json` file in your project directory:

```json
{
  "default_server": "localhost",
  "default_database": "master",
  "connection_timeout": 30,
  "pool_size": 10,
  "log_level": "INFO",
  "output_format": "table"
}
```

## 📚 Usage Examples

### MCP Client Integration

```python
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    # Connect to SQL Server MCP Server
    server_params = StdioServerParameters(
        command="python",
        args=["-m", "src.mcp_tools"]
    )
    
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            # Initialize the session
            await session.initialize()
            
            # Create a database connection
            result = await session.call_tool(
                "create_connection",
                {
                    "server": "localhost",
                    "database": "master",
                    "trusted_connection": True
                }
            )
            
            connection_id = result.content[0].text
            
            # Execute a query
            query_result = await session.call_tool(
                "execute_query",
                {
                    "query": "SELECT name FROM sys.databases",
                    "connection_id": connection_id
                }
            )
            
            print(query_result.content[0].text)

if __name__ == "__main__":
    asyncio.run(main())
```

### CLI Examples

```bash
# Connect to SQL Server
sqlserver-mcp connect --server "localhost" --database "AdventureWorks" --trusted-connection

# List all databases
sqlserver-mcp list-databases --connection-id conn_123

# Get table schema
sqlserver-mcp get-schema --connection-id conn_123 --table "Person.Person" --include-relationships

# Execute parameterized query
sqlserver-mcp query --connection-id conn_123 "SELECT * FROM Person.Person WHERE BusinessEntityID = @id" --params '{"id": 1}'

# Get table data with pagination
sqlserver-mcp select --connection-id conn_123 --table "Person.Person" --limit 10 --offset 0

# Export query results to CSV
sqlserver-mcp query --connection-id conn_123 "SELECT * FROM Person.Person" --output-format csv > results.csv
```

## 🧪 Testing

The project includes comprehensive test coverage:

- **Contract Tests**: Validate MCP protocol compliance
- **Integration Tests**: Test with real SQL Server instances
- **Unit Tests**: Test individual components
- **Performance Tests**: Benchmark query execution and connection management

### Running Tests

```bash
# Run all tests
pytest

# Run specific test categories
pytest tests/contract/     # Contract tests
pytest tests/integration/  # Integration tests  
pytest tests/unit/        # Unit tests
pytest tests/performance/ # Performance tests

# Run with coverage
pytest --cov=src --cov-report=html
```

## 🏗️ Architecture

The SQL Server MCP Server follows a modular architecture:

```
src/
├── mcp_tools/          # MCP protocol implementation
│   ├── execute_query_tool.py
│   ├── get_schema_tool.py
│   ├── list_databases_tool.py
│   ├── get_table_data_tool.py
│   ├── create_connection_tool.py
│   └── mcp_server.py
├── services/           # Business logic services
│   ├── connection_manager.py
│   ├── query_executor.py
│   ├── schema_service.py
│   └── data_service.py
├── models/             # Data models
│   ├── connection.py
│   ├── query.py
│   ├── schema.py
│   └── data.py
├── cli/                # Command-line interface
│   ├── connection_commands.py
│   ├── query_commands.py
│   ├── schema_commands.py
│   ├── data_commands.py
│   └── config_commands.py
└── lib/                # Shared utilities
    ├── config.py
    ├── logging.py
    ├── exceptions.py
    └── performance.py
```

## 🔧 Development

### Setup Development Environment

```bash
# Clone the repository
git clone https://github.com/your-org/sqlserver-mcp-server.git
cd sqlserver-mcp-server

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install development dependencies
pip install -e ".[dev]"
```

### Code Quality

```bash
# Format code
black src/ tests/
isort src/ tests/

# Lint code
flake8 src/ tests/
mypy src/

# Run all quality checks
make lint
```

### Testing

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=src --cov-report=html

# Run specific test categories
pytest tests/contract/     # Contract tests
pytest tests/integration/  # Integration tests
pytest tests/unit/        # Unit tests
pytest tests/performance/ # Performance tests
```

### Building

```bash
# Build package
python -m build

# Install from built package
pip install dist/sqlserver_mcp_server-*.whl
```

## 📋 Roadmap

- [ ] Support for additional database engines (PostgreSQL, MySQL)
- [ ] Advanced query optimization and caching
- [ ] Real-time database monitoring and alerts
- [ ] Enhanced security features (encryption, audit logging)
- [ ] Web-based administration interface
- [ ] Docker containerization and Kubernetes support

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](docs/CONTRIBUTING.md) for details.

### Development Workflow

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for your changes
5. Run the test suite (`pytest`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

## 📄 License

This project is licensed under the GNU Lesser General Public License v3.0 - see the [LICENSE](LICENSE) file for details.

## 🆘 Support

- 📖 **Documentation**: Check the [docs/](docs/) directory for detailed documentation
- 🐛 **Bug Reports**: Create a [GitHub issue](https://github.com/your-org/sqlserver-mcp-server/issues)
- 💡 **Feature Requests**: Create a [GitHub issue](https://github.com/your-org/sqlserver-mcp-server/issues)
- 💬 **Discussions**: Join our [GitHub Discussions](https://github.com/your-org/sqlserver-mcp-server/discussions)
- 📧 **Email**: Contact us at support@your-org.com

## 🙏 Acknowledgments

- [Model Context Protocol](https://modelcontextprotocol.io/) for the MCP specification
- [pyodbc](https://github.com/mkleehammer/pyodbc) for SQL Server connectivity
- [Pydantic](https://pydantic.dev/) for data validation
- [Click](https://click.palletsprojects.com/) for CLI framework
- [Rich](https://rich.readthedocs.io/) for beautiful terminal output

## 📊 Project Status

![GitHub last commit](https://img.shields.io/github/last-commit/your-org/sqlserver-mcp-server)
![GitHub issues](https://img.shields.io/github/issues/your-org/sqlserver-mcp-server)
![GitHub pull requests](https://img.shields.io/github/issues-pr/your-org/sqlserver-mcp-server)
![GitHub stars](https://img.shields.io/github/stars/your-org/sqlserver-mcp-server)